Site icon JS Tech Road

PHP Cheat Sheet

Including PHP in a File

<?php

// place PHP code here

?>

Writing Comments

Outputting Data

In PHP, data is commonly output using echo or print. For example, the title of this blog post might be displayed on a page like this:

<?php
    echo "<h2>Hello World!</h2>";
?>

The two commands echo and print are pretty much the same. The only difference is that the former has no return value and can take several parameters, while the latter has a return value of 1 and can only take one argument.

Note: Like all other PHP commands, functions echo and print are not case sensitive. That means that when you write ECHOEcHoeCHO or any other variation, they will continue to work. As you will learn further on, that doesn’t apply to everything.

Writing PHP Functions

function NameOfTheFunction() {
    // PHP code here
}

Quick explanation: the first part is the function of a name (reminder: function names are not case sensitive). After that, everything between the curly braces is what the function does when called.

Defining Variables

In PHP, you denote a variable using the $ sign and assign its value using =. A typical example:

<?php
   $title = "PHP Cheat Sheet";
?>

Note:

Types of Data

There is no need to declare PHP variables in a certain way. They automatically take on the type of data they contain.

Variable Scope

Variables can be available in different scopes, meaning the part of a script you can access them. This can be globallocal and static.

Any variable declared outside of a function is available globally. That means it can be accessed outside of a function as well.

If you declare a variable inside a function, it will have a local scope. The consequence is that it can only be accessed within that function.

A way around this is to prepend a local variable with global. That way, it becomes part of the global scope:

function myFunction() {
    global $a, $b;
    $b = $a - $b;
}

In both cases, the variable becomes part of the $GLOBALS variable mentioned below.

Finally, it’s also possible to add static in front of a local variable. That way, it won’t be deleted after its function is executed and can be reused.

Predefined Variables

Reserve PHP variables, accessible from anywhere, regardless of scope.

Variable-Handling Functions

There are a whole bunch of functions to work with variables:

Constants

Aside from variables, you can also define constants which also store values. In contrast to variables their value can not be changed, it’s locked in.

In PHP you can define a constant:

define(name, value, true/false)

The first is the name, the second the constant’s value and the third parameter whether its name should be case sensitive (the default is false).

Constants are useful since they allow you to change the value for an entire script in one place instead of having to replace every instance of it. They are also global in nature, meaning they can be accessed from anywhere.

Aside from user-defined constants, there also a number of default PHP constants:

PHP Arrays – Grouped Values

Arrays are a way to organize several values in a single variable so that they can be used together. While functions are for blocks of code, arrays are for the values – a placeholder for larger chunks of information.

In PHP there are different types of arrays:

Declaring an Array in PHP

Arrays in PHP are created with the array()

<?php
  $cms = array("Banna", "Apple", "Pear");
  echo "What is your favorite fruit? Is it " . $cms[0] . ", " . $cms[1] . " or " . $cms[2] . "?";
?>

Array keys can either be strings or integers.

How to create an array with key value pairs in PHP?

PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows:

Syntax 1: Using array() constructor

$arrayVariable = array(
    key1 => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
);

Syntax 2: Using shorthand notation

$arrayVariable = [
    key1 => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
];

Array Functions

PHP Strings

In programming, speech strings are nothing more than text. As we have settled earlier, they are also a valid value for variables.

Defining Strings

In PHP there are several ways to define strings:

Note: Strings can contain variables, arrays, and objects.

Escape Characters

String Functions

PHP Operators

Operators allow you to perform operations with values, arrays, and variables. There are several different types.

Arithmetic Operators

Your standard mathematic operators.

Assignment Operators

Besides the standard assignment operator (=), you also have the following options:

Comparison Operators

Logical Operators

Bitwise Operators

Error Control Operator

You can use the @ sign to prevent expressions from generating error messages. This is often important for security reasons, for example, to keep confidential information safe.

Execution Operator

PHP supports one execution operator, which is `` (backticks). These are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command.

Increment/Decrement Operators

String Operators

Loops in PHP

Loops are very common in programming. They allow you to run through the same block of code under different circumstances. PHP has several different ones.

For Loop

This type goes through a block of code a specified number of times:

for ($i = 0; $i <= 10; $i++) {
    // code to execute goes here
}

Foreach Loop

A loop using foreach runs through each element in an array:

foreach ($InsertYourArrayName as $value) {
    // code to execute goes here
}
// or
foreach ($array as $key => $value)

While Loop

Loops through a block of code as long as a specified condition is true.

while (condition that must apply) {
    // code to execute goes here
}

Do…While Loop

The final PHP loop runs a code snippet once, then repeats the loop as long as the given condition is true.

do {
    // code to execute goes here;
} while (condition that must apply);

Conditional Statements

If/else statements are similar to loops. They are statements for running code only under certain circumstances. You have several options:

If/elseif/else Statement

if (condition) {
    // code to execute if condition is met
} elseif (condition) {
    // code to execute if this condition is met
} else {
    // code to execute if none of the conditions are met
}

Switch Statement

switch (n) {
    case 1:
        code to execute if n=1;
        break;
    case 'abc':
        code to execute if n='abc';
        break;
    case z:
        code to execute if n=z;
        break;
    // add more cases as needed
    default:
        code to execute if n is neither of the above;
}

Working with Forms in PHP

$_GET and $_POST help to collect data sent via a form.

Using GET vs POST

GET collects data via URL parameters. That means all variable names and their values are contained in the page address.

The advantage of this is that you’re able to bookmark the information. Keep in mind that it also means that the information is visible to everyone. For that reason, GET is not suitable for sensitive information such as passwords. It also limits the amount of data that can be sent in ca 2000 characters.

POST, on the other hand, uses the HTTP POST method to pass on variables. This makes the data invisible to third parties, as it is sent in the HTTP body. You are not able to bookmark it.

With POST, there are no limits to the amount of information you can send. Aside from that, it also has advanced functionality and is therefore preferred by developers.

Form Security

The most important issue when it comes to web forms is security. If not set up properly, they are vulnerable to cross-scripting attacks. The hackers add scripts to unsecured web forms to use them for their own purpose.

PHP offers following function to thwart those attacks:

Required Fields, Error Messages and Data Validation

PHP is able to define required fields (you can’t submit the form without filling them out), display error messages if some information is missing and to validate data. We have already talked about the necessary tools to do so.

For example, you can simply define variables for your form fields and use the empty() function to check if they have values. After that, create a simple if/else statement to either send the submitted data or output an error message.

The next step is to check the submitted data for validity. For that, PHP offers a number of filters such as FILTER_VALIDATE_EMAIL to make sure a submitted email address has the right format.

Regular Exprressions (RegEx)

Syntax

$exp = "/w3schools/i";

RegEx Functions

preg_match()

Returns 1 if the pattern was found in the string and 0 if not

preg_match_all()

Returns the number of times the pattern was found in the string, which may also be 0

preg_replace()

Returns a new string where matched patterns have been replaced with another string

RegEx Modifiers

i Performs a case-insensitive search

m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)

u Enables correct matching of UTF-8 encoded patterns

RegEx Patterns

[abc] – Find one character from the options between the brackets

[^abc] – Find any character NOT between the brackets

[0-9] – Find one character from the range 0 to 9

Metacharacters

| Find a match for any one of the patterns separated by | as in: cat|dog|fish

. Find just one instance of any character

^ Finds a match as the beginning of a string as in: ^Hello

$ Finds a match at the end of the string as in: World$

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{x} Matches any string that contains a sequence of X n’s

n{x,y} Matches any string that contains a sequence of X to Y n’s

n{x,} Matches any string that contains a sequence of at least X n’s

Grouping

Use parentheses ( ) to apply quantifiers to entire patterns. They cal also be used to select parts of the pattern to be used as a match.

<?php
  $str = "Apples and bananas.";
  $pattern = "/ba(na){2}/i";
  echo preg_match($pattern, $str); // Outputs 1
?>

PHP Functions

Default Argument Value

<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 100) {
  echo "The height is : $minheight <br>";
}
setHeight(50);
setHeight(); // will use the default value of 100

?>

PHP Filters

Filters are used to validate and filter data that is coming from insecure sources. As mentioned, a common example is user input. PHP offers a number of filter functions and constants for that:

Filter Functions

Filter Constants

HTTP Functions in PHP

PHP also has the functionality to manipulate data sent to the browser from the webserver.

HTTP Functions

Working with MySQL

Many platforms that are based on PHP work with a MySQL database in the background.

MySQL Functions

Date/Time Functions

Date and Time Formatting

PHP Errors

Error Functions

Error Constants

Exit mobile version