$).a-z, A-Z, or _.a-z, A-Z, 0-9, or _.PHP can be used in three main fields:
PHP was designed to work closely with HTML for dynamic behavior. PHP content is executed on the server and added to the HTML to form one HTML document before being sent to the client.
Three types of tags are available in PHP:
<?php ?><?= ?><? ?>Note: Short tags are by default available but can be disabled by
short_open_tag = Offand also disabled by default if PHP is built with--disable-short-tags(). Note: The closing tag of a PHP block at the end of a file is optional. Omitting it can be helpful when usingincludeorrequireto prevent unwanted whitespace at the end of files, allowing you to add headers to the response later. Note: If PHP is embedded within XML or XHTML, the normal<?php ?>tags must be used to remain compliant with the standards. Note: PHP requires instructions to be terminated with a semicolon (;) at the end of each statement.
strcmp() Type JugglingThe strcmp() function in PHP typically expects two strings. However, prior to PHP 8.0, if strcmp() is given an array instead of a string, it returns NULL and generates a Warning. In loose comparisons (==), NULL is treated as equal to 0. Since strcmp() returns 0 when strings match, this behavior can be misinterpreted as a successful match if the check is written as if (strcmp($a, $b) == 0).
Vulnerable Code Example:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// If $password is an array (e.g., password[]=1), strcmp returns NULL.
// NULL == 0 is TRUE in PHP loose comparison.
if (strcmp($password, $stored_password) == 0) {
// Login bypassed!
}
?>
Fix:
Use the strict comparison operator (===) or ensure inputs are strings.
<?php
if (strcmp($password, $stored_password) === 0) {
// ...
}
?>
Or better, use hash_equals() for comparing sensitive strings like password hashes to prevent timing attacks.
<?php
session_start();
if (!empty($_POST['username']) && !empty($_POST['password'])) {
require('config.php');
if (strcmp($username, $_POST['username']) == 0) {
if (strcmp($password, $_POST['password']) == 0) {
$_SESSION['user_id'] = 1;
header("Location: /upload.php");
} else {
print("<script>alert('Wrong Username or Password')</script>");
}
} else {
print("<script>alert('Wrong Username or Password')</script>");
}
}
?>
echo and print Statementsecho and print are both used to output data to the screen. When used within HTML, they output to the HTML document rather than the terminal.
The PHP opening (<?php) and closing (?>) tags are used to insert PHP code in HTML pages. The echo statement adds text to HTML. PHP provides a shorthand syntax <?= instead of <?php echo.
Differences:
echo has no return value, while print has a return value of 1 (so it can be used in expressions).echo can take multiple parameters (though rare), while print takes only one argument.echo is marginally faster than print.Output Functions:
print: Outputs a string.printf: Outputs a formatted string.print_r: Prints human-readable information about a variable, mostly used for compound types (arrays, objects, etc.).echo Examples:
<?php
echo("This works!\n");
echo "This also works!\n";
// echo("This would NOT work", "\n"); // Multiple parameters require parentheses for echo.
echo "Buuuut!", " ", "This", " ", "does!", "\n";
?>
include & require StatementsThe include or require statement inserts the content of one PHP file into another PHP file before server execution.
Differences upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script.include will only produce a warning (E_WARNING) and the script will continue.If you want execution to continue even if the included file is missing, use include. If the file is critical (e.g., in a framework or complex application), always use require to avoid compromising security and integrity. Including files saves work by allowing you to create standard headers, footers, or menu files that can be updated in one place.
PHP supports ten primitive types.
Scalar values are values that cannot be broken into smaller pieces.
boolintfloatstringarrayobjectcallableiterableRESOURCENULLThe type of a variable is usually decided at runtime by PHP. To forcibly convert a variable, either cast it or use the settype() function.
var_dump(): Checks the type and value of an expression.gettype(): Returns a human-readable representation of a type.is_type() functions (is_int(), is_string(), is_bool()): Check for a certain type.PHP strings allow direct variable placement within double-quoted strings, where variables will be parsed (their values will be used). PHP also has leading numeric strings, which start with a numeric string followed by any characters.
Note: Any string that contains the letter
E(case insensitive) bounded by numbers will be seen as a number expressed in scientific notation. This can produce unexpected results.
<?php
var_dump("0D1" == "000"); // false, "0D1" is not scientific notation
var_dump("0E1" == "000"); // true, "0E1" is 0 * (10 ^ 1), or 0
var_dump("2E1" == "020"); // true, "2E1" is 2 * (10 ^ 1), or 20
?>
During variable assignment, the left variable is the storage, and the right variable's value is stored.
=&). Both names point to the same memory location, so changes to one affect the other.If PHP encounters a number beyond the bounds of the int type, it will be interpreted as a float. Operations that result in numbers outside the int range will also return a float.
Warning:
-1is consideredtrue, like any other non-zero number.
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation. The negation operator can be used for negative integers.
0 (or 0o / 0O as of PHP 8.1.0).0x.0b.When converting to bool, the following values are considered false:
false itself0 (zero)0.0 and -0.0 (zero)""), and the string "0"NULL (including unset variables)SimpleXML objects created from attributeless empty elements.Every other value is considered true (including any resource and NAN).
An array in PHP is an ordered map that associates values with keys. Arrays can be created using the array() language construct or the short array syntax ([]).
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
Keys can be integers or strings. If no key is specified, PHP will assign the next available integer key (maximum integer key + 1, or 0 if no integer keys exist).
<?php
$array = array(
1 => 'a',
'1' => 'b', // 'a' will be overwritten by 'b'
1.5 => 'c', // 'b' will be overwritten by 'c'
-1 => 'd',
'01' => 'e', // Not an integer string, does not override key for 1
'1.5' => 'f', // Not an integer string, does not override key for 1
true => 'g', // 'c' will be overwritten by 'g'
false => 'h',
'' => 'i',
null => 'j', // 'i' will be overwritten by 'j'
'k', // Value 'k' is assigned the key 2 (largest int key + 1)
2 => 'l', // 'k' will be overwritten by 'l'
);
var_dump($array);
?>
Associative arrays use key => value pairs. The key must be a string or an integer. Values can be of any type. Elements can be removed using unset().
The union (+) operator for arrays appends unique keys from the second array to the first. If keys are the same, the left array's value takes precedence.
An iterable is any value that can be looped through with a foreach() loop (arrays or instances of Traversable). It can be used as a parameter type or return type for functions.
Iterable Parameter Type Example:
<?php
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
?>
Iterable Parameter Default Value Example:
<?php
function foo (iterable $iterable = []) {
// ...
}
?>
Return an Iterable Example:
<?php
function getIterable() :iterable {
return ["a", "b", "c"];
}
$myIterable = getIterable();
foreach($myIterable as $item) {
echo $item; // Prints abc
}
?>
A RESOURCE is a special variable holding a reference to an external resource, created and used by special functions.
The special null value represents a variable with no value. A variable is considered null if:
null.unset().<?php
$var = NULL;
?>
Operations have an order of precedence (PEMDAS): parentheses (()), exponents (**), multiplication (*) and division (/), then addition (+) and subtraction (-).
| Operation | Long Syntax | Short Syntax |
|---|---|---|
| Add | $x = $x + $y | $x += $y |
| Subtract | $x = $x - $y | $x -= $y |
| Multiply | $x = $x * $y | $x *= $y |
| Divide | $x = $x / $y | $x /= $y |
| Modulo | $x = $x % $y | $x %= $y |
Note: Increment/decrement operators only affect numbers and strings. Arrays, objects, booleans, and resources are not affected. Decrementing
nullhas no effect, but incrementing it results in1.
| Example | Name | Effect |
|---|---|---|
++$a | Pre-increment | Increments $a by one, then returns $a. |
$a++ | Post-increment | Returns $a, then increments $a by one. |
--$a | Pre-decrement | Decrements $a by one, then returns $a. |
$a-- | Post-decrement | Returns $a, then decrements $a by one. |
$a++, $a--): Use then change.++$a, --$a): Change then use.<?php
$n = 3;
echo $n--; // 3 (returns 3, then $n becomes 2)
echo --$n; // 1 ($n becomes 1, then returns 1)
echo $n; // 1
?>
Note: The argument spread operator (
...) is not supported in assignments.
PHP does not require explicit type definition. The type of a variable is determined by the value it stores. PHP may attempt to convert the type of a value automatically in certain contexts:
echo, print, string interpolation, or concatenation. Values are interpreted as strings.Note: When a value needs to be interpreted as a different type, the value itself does not change types permanently.
Type casting converts a value to a chosen type by writing the type within parentheses before the value.
<?php
$foo = 10; // $foo is an integer
$bar = (bool) $foo; // $bar is a boolean
?>
Allowed Casts:
(int): Cast to integer(bool): Cast to boolean(float): Cast to float(string): Cast to string(array): Cast to array(object): Cast to object(unset): Cast to NULLType declarations can be added to function arguments, return values, and class properties to ensure the value is of the specified type at call time, throwing a TypeError otherwise. When overriding a parent method, the child's method must match the parent's return type declaration.
Single Types:
| Type | Description |
|---|---|
Class/interface | The value must be an instance of the given class or interface. |
self | The value must be an instance of the same class as the one in which the type declaration is used. (Classes only) |
parent | The value must be an instance of the parent of the class in which the type declaration is used. (Classes only) |
array | The value must be an array. |
callable | The value must be a valid callable. (Cannot be used as a class property type declaration) |
bool | The value must be a boolean value. |
float | The value must be a floating-point number. |
int | The value must be an integer. |
string | The value must be a string. |
iterable | The value must be either an array or an instance of Traversable. |
object | The value must be an object. |
mixed | The value can be any type. |
When a function is assigned to a variable, the return value of the function is indirectly assigned to that variable.
<?php
function myFunction() {
return "value";
}
$thisMyFunction = myFunction(); // Executes myFunction() and assigns "value" to $thisMyFunction
?>
The return keyword immediately stops a function. Any code after a return statement will not run. A function without a return statement implicitly returns NULL.
Default arguments prevent errors if a function is invoked without a required argument.
<?php
function myFunction($param = "argument") {
// ...
}
?>
By default, when a variable is passed as an argument, a copy of its value is used. Changes to the parameter inside the function do not affect the original variable. To make permanent changes, prepend the parameter name with an ampersand (&) to pass by reference. Both the argument and parameter will then refer to the same memory location.
<?php
function addX ($param) {
$param = $param . "X";
echo $param;
}
function addXPermanently (&$param) {
$param = $param . "X";
echo $param;
}
$word = "Hello";
addX($word); // Prints: HelloX
echo $word; // Prints: Hello
$word = "Hello";
addXPermanently($word); // Prints: HelloX
echo $word; // Prints: HelloX
?>
The scope of a variable is the context within which it is defined. In PHP, global variables must be declared global inside a function to be used within that function. Each function has its own local scope, meaning variables defined inside a function are only accessible within it. The global keyword tells PHP to look in the global scope for the variable.
gettype(): Takes a variable and returns a string representing its data type.var_dump(): Prints detailed information about a variable (value and type).strrev(): Takes a string and returns it with characters in reverse order.strtolower(): Transforms a string into all lowercase letters.str_repeat(string, number): Returns a string with the argument string repeated a specified number of times.substr_count(haystack, needle): Returns the number of instances of a substring within a string.abs(): Returns the absolute value of a number.round(): Returns the nearest integer to a number.rand(): Returns a random integer. Invoked without arguments, it returns a number between 0 and the largest allowed number in the environment.There are 12 predefined variables in PHP 8 that are "superglobals," meaning they are always accessible regardless of scope.
$GLOBALS: An associative array containing references to all variables currently defined in the global scope.
$_SERVER: An array containing information such as headers, paths, and script locations. Its entries are created by the web server.
$_GET: An associative array of variables passed to the current script via URL parameters.
$_POST: An associative array of variables passed to the current script via the HTTP POST method.
GET vs. POST: Both create associative arrays (key => value) holding input data.
HTML forms often use the action attribute to specify the PHP file to process the form data.
$_REQUEST: A superglobal variable used to collect data after submitting an HTML form. It contains the contents of $_GET, $_POST, and $_COOKIE.
$_COOKIE: An associative array of variables passed to the current script via HTTP Cookies. A cookie is created with setcookie().
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. setcookie() must appear BEFORE the <html> tag.
$_ENV: An associative array of variables passed to the current script via the environment.
$argc: Contains the number of arguments passed to the current script when run from the command line. The script's filename is always the first argument, so $argc's minimum value is 1. Also available as $_SERVER['argc'].
$argv: Contains an array of all arguments passed to the script when run from the command line. The first argument ($argv[0]) is always the script's name. Also available as $_SERVER['argv'].
$_FILES: Handles uploaded file information.
HTML form for file upload:
<form enctype="multipart/form-data" action="__URL__" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
Note: The
enctype="multipart/form-data"attribute is crucial for file uploads to work. The__URL__should be replaced with the path to the PHP handler script.
$_SESSION: Used to set session variables, which store information across multiple pages without being stored on the user's computer (unlike cookies). Sessions are started with session_start() (must be the very first thing in the document). session_unset() removes all session variables, and session_destroy() destroys the session.
A class may contain its own constants, variables (properties), and functions (methods). Objects are specific instances of a class, created through instantiation using the new keyword.
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
->): Used to interact with an object's properties and methods.$this: Refers to the current object and is available when a method is called from within an object context.Declaring class properties or methods as static makes them accessible without needing an instance of the class. $this is not available inside static methods. Static properties and methods are accessed using the Scope Resolution Operator (::) (self::$property or ClassName::method()) and cannot be accessed through the object operator (->).
Constants are declared with the const keyword inside a class and cannot be changed. They are case-sensitive (conventionally uppercase). Access from outside: ClassName::CONSTANT_NAME. Access from inside: self::CONSTANT_NAME.
Methods are functions defined within a class. They are accessed using the object operator (->) followed by parentheses (()) to invoke them.
__construct()): An ordinary method automatically called during object instantiation. It can define arguments (parameters).__destruct()): Automatically called when the object is destroyed or the script ends.Classes can inherit from other classes using the extends keyword. A class can only inherit from one parent class. A subclass inherits all public and protected methods, properties, and constants from the parent. private methods are not inherited.
<?php
class ChildClass extends ParentClass {
// ...
}
?>
Child classes can override parent methods by defining a new method with the same name. parent:: can be used to call the parent's method from within the child class.
Note: The
finalkeyword can prevent class inheritance or method overriding.
Three levels of visibility for class members:
public (default): Accessible from anywhere (inside or outside the class).protected: Accessible only within the class and its descendants.private: Accessible only within the defining class itself.The concept of accessing properties only through methods is called using getters and setters. Getters (getName()) retrieve property values, and setters (setName($name)) set them, often including logic for validation or formatting.
<?php
class Pet {
private $name;
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
}
?>
::)The double colon (::) allows access to static, constant, and overridden properties or methods. self, parent, and static keywords are used with :: from inside the class definition.
An exception is an object that describes an error or unexpected behavior. Exceptions are thrown by PHP functions and classes, and by user-defined functions using the throw statement.
<?php
try {
// Code that can throw exceptions
} catch(Exception $e) {
// Code that runs when an exception is caught
}
?>
The catch block specifies the type of exception to catch (e.g., Exception) and a variable name ($e) to access the exception object.
Creating Exceptions:
<?php
new Exception(message, code, previous);
?>
message: (Optional) String describing the exception.code: (Optional) Integer code for distinguishing exceptions.previous: (Optional) The previous exception if this one was thrown in a catch block.Exception Object Methods:
getMessage(): Returns the exception message.getPrevious(): Returns the previous exception object, or null.getCode(): Returns the exception code.getFile(): Returns the full path of the file where the exception was thrown.getLine(): Returns the line number where the exception was thrown.PHP can connect to and manipulate databases, with MySQL being the most popular. Data is stored in tables.
Prepared statements are a crucial security feature against SQL injection and improve efficiency for repeated SQL statements.
How they work:
?). The database parses, compiles, and optimizes the template.
Example: INSERT INTO MyGuests VALUES(?, ?, ?)Advantages of Prepared Statements:
Three ways to work with PHP and MySQL: