PHP
A comprehensive PHP cheatsheet
PHP Cheatsheet
1. Introduction to PHP
PHP (PHP: Hypertext Preprocessor) is a server-side scripting language used to build dynamic websites and web applications. PHP code executes on the server, and its output can be sent to a browser as HTML, JSON, or other content.
Common uses of PHP include:
- Dynamic websites and web applications
- Form processing and validation
- Database operations
- Authentication and session management
- REST APIs
- Content management systems such as WordPress
Basic PHP Syntax
<?php echo "Hello, World!"; ?>
<?phpstarts a PHP code block.echodisplays output.;terminates most PHP statements.?>closes a PHP block, but it is commonly omitted in PHP-only files.
Running PHP
Save the code in index.php and run:
php index.php
To start PHP's built-in development server:
php -S localhost:8000
Then open http://localhost:8000 in your browser.
2. Comments
// Single-line comment # Single-line comment /* Multi-line comment */
Comments are ignored during program execution.
3. Variables
Variables store data and begin with $.
<?php $name = "Uday"; $age = 23; $price = 99.50; $isActive = true; echo $name; echo $age; ?>
Variable Rules
- A variable starts with
$. - The name must begin with a letter or underscore after
$. - Variable names are case-sensitive.
- Names cannot contain spaces.
$name = "Uday"; $Name = "Rahul"; // Different variable
Variable Scope
PHP supports local, global, static, and parameter variables.
$x = 10; function showValue() { global $x; echo $x; } showValue();
A static variable retains its value between function calls:
function counter() { static $count = 0; $count++; echo $count; } counter(); // 1 counter(); // 2
4. Data Types
PHP supports the following main data types:
| Type | Example |
|---|---|
| Integer | $age = 23; |
| Float | $price = 10.5; |
| String | $name = "Uday"; |
| Boolean | $active = true; |
| Array | $numbers = [1, 2, 3]; |
| Object | $user = new User(); |
| NULL | $value = null; |
| Resource | $file = fopen("data.txt", "r"); |
Use var_dump() to inspect a value and its type.
$value = 25; var_dump($value);
Output:
int(25)
5. Constants
Constants store values that cannot be reassigned after definition.
define("SITE_NAME", "Ugenz Academy"); const VERSION = "1.0"; echo SITE_NAME; echo VERSION;
Unlike variables, constants are accessed without $.
6. Output Statements
echo
echo "Hello"; echo "Hello", " PHP";
print
print "Hello, World!";
Both display output. echo can output multiple arguments, while print accepts one argument and returns 1.
printf()
$name = "Uday"; $age = 23; printf("Name: %s, Age: %d", $name, $age);
Common format specifiers include %s for strings, %d for integers, and %f for floating-point values.
7. Strings
$name = "Uday"; echo strlen($name); echo strtoupper($name); echo strtolower($name); echo ucfirst("php programming"); echo trim(" Hello "); echo str_replace("PHP", "Python", "Learn PHP"); echo substr("Programming", 0, 4);
String Concatenation
PHP uses . to join strings.
$first = "Uday"; $last = "Raut"; echo $first . " " . $last;
String Interpolation
$name = "Uday"; echo "Hello, $name"; echo "Hello, {$name}";
Single-quoted strings generally do not interpolate variables.
8. Operators
Arithmetic Operators
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
** | Exponentiation |
$a = 10; $b = 3; echo $a + $b; echo $a % $b; echo $a ** $b;
Assignment Operators
$x = 10; $x += 5; $x -= 2; $x *= 3; $x /= 2; $x %= 4;
Comparison Operators
$a == $b; // Equal after type juggling $a === $b; // Equal value and same type $a != $b; // Not equal $a !== $b; // Not identical $a > $b; $a < $b; $a >= $b; $a <= $b;
Prefer === and !== when type-sensitive comparison is required.
Logical Operators
$a && $b; // AND $a || $b; // OR !$a; // NOT $a and $b; $a or $b; $a xor $b;
Note that and and or have different precedence from && and ||.
Other Operators
$x = 5; $x++; // Increment $x--; // Decrement $name = $input ?? "Guest"; // Null coalescing $result = $a <=> $b; // Spaceship operator
The null coalescing operator uses the fallback when the left operand is missing or null.
9. Conditional Statements
if, elseif, and else
$marks = 75; if ($marks >= 80) { echo "Excellent"; } elseif ($marks >= 50) { echo "Pass"; } else { echo "Fail"; }
switch
$day = 2; switch ($day) { case 1: echo "Monday"; break; case 2: echo "Tuesday"; break; default: echo "Unknown day"; }
match (PHP 8.0+)
$status = 200; $message = match ($status) { 200 => "OK", 404 => "Not Found", 500 => "Server Error", default => "Unknown" }; echo $message;
Unlike switch, match uses strict comparison and returns a value.
10. Loops
for
for ($i = 1; $i <= 5; $i++) { echo $i . "\n"; }
while
$i = 1; while ($i <= 5) { echo $i; $i++; }
do-while
$i = 1; do { echo $i; $i++; } while ($i <= 5);
A do-while loop executes its body at least once.
foreach
$fruits = ["Apple", "Mango", "Banana"]; foreach ($fruits as $fruit) { echo $fruit . "\n"; }
For key-value pairs:
$user = [ "name" => "Uday", "age" => 23 ]; foreach ($user as $key => $value) { echo "$key: $value\n"; }
Use break to exit a loop and continue to skip to the next iteration.
11. Arrays
Arrays store multiple values in one variable.
Indexed Arrays
$colors = ["Red", "Green", "Blue"]; echo $colors[0];
Associative Arrays
$user = [ "name" => "Uday", "age" => 23 ]; echo $user["name"];
Multidimensional Arrays
$students = [ ["Uday", 80], ["Rahul", 90] ]; echo $students[0][0]; echo $students[1][1];
Common Array Functions
$numbers = [3, 1, 2]; count($numbers); sort($numbers); rsort($numbers); array_push($numbers, 4); array_pop($numbers); array_merge([1, 2], [3, 4]); in_array(2, $numbers); array_keys(["name" => "Uday"]); array_values(["name" => "Uday"]);
sort() and rsort() reindex numeric keys. Use asort() or ksort() when preserving associative keys is important.
Spread Operator
$a = [1, 2]; $b = [...$a, 3, 4];
12. Functions
Functions organize reusable code.
function greet() { echo "Hello, World!"; } greet();
Parameters and Return Values
function add(int $a, int $b): int { return $a + $b; } echo add(10, 20);
Default Parameters
function greetUser(string $name = "Guest"): string { return "Hello, $name"; }
Named Arguments (PHP 8.0+)
function introduce(string $name, int $age): void { echo "$name is $age years old"; } introduce(age: 23, name: "Uday");
Variable-Length Arguments
function sum(int ...$numbers): int { return array_sum($numbers); } echo sum(1, 2, 3, 4);
Anonymous Functions
$multiply = function ($a, $b) { return $a * $b; }; echo $multiply(3, 4);
Arrow Functions (PHP 7.4+)
$numbers = [1, 2, 3]; $squares = array_map( fn($n) => $n * $n, $numbers );
13. Type Declarations
PHP supports parameter types, return types, and property types.
function calculate(float $price, int $quantity): float { return $price * $quantity; }
Common types include int, float, string, bool, array, object, callable, iterable, and class or interface names.
Union types (PHP 8.0+):
function display(int|string $value): void { echo $value; }
Nullable types:
function findName(): ?string { return null; }
Strict typing:
<?php declare(strict_types=1); function double(int $number): int { return $number * 2; }
Place declare(strict_types=1); at the beginning of the PHP file, after the opening tag. Strict typing primarily affects scalar type declarations at calls made from that file.
14. Superglobal Variables
Superglobals are built-in variables available throughout a PHP script.
| Variable | Purpose |
|---|---|
$_GET | Query-string parameters |
$_POST | Form data sent using POST |
$_REQUEST | Combined request data, depending on configuration |
$_SERVER | Request and server information |
$_SESSION | Session data |
$_COOKIE | Cookie values |
$_FILES | Uploaded-file information |
$_ENV | Environment variables |
$GLOBALS | Global variables |
Example:
echo $_SERVER["REQUEST_METHOD"];
Never assume values from request-related superglobals are trusted.
15. HTML Forms and PHP
HTML Form
<form method="post" action="process.php"> <input type="text" name="username" required> <button type="submit">Submit</button> </form>
Processing the Form
<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { $username = trim($_POST["username"] ?? ""); if ($username !== "") { echo "Hello, " . htmlspecialchars( $username, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8" ); } }
htmlspecialchars() helps prevent HTML injection when displaying user input in an HTML context. It does not replace validation or context-specific output encoding in other contexts.
16. GET and POST
GET
$name = $_GET["name"] ?? "Guest"; echo htmlspecialchars($name, ENT_QUOTES, "UTF-8");
Example URL:
http://localhost:8000/index.php?name=Uday
GET parameters appear in the URL and should not be used for secrets.
POST
$email = $_POST["email"] ?? "";
POST sends data in the request body. It does not automatically encrypt data; use HTTPS for transport security.
17. Include and Require
These statements reuse code from other files.
include "header.php"; include_once "config.php"; require "database.php"; require_once "functions.php";
include: raises a warning if the file cannot be loaded.require: raises an error that stops normal execution if the file cannot be loaded.include_onceandrequire_once: avoid loading the same file multiple times.
18. File Handling
Read a File
$content = file_get_contents("data.txt"); echo $content;
Write a File
file_put_contents("data.txt", "Hello PHP");
Append to a File
file_put_contents( "data.txt", "\nNew line", FILE_APPEND );
Using fopen()
$file = fopen("data.txt", "r"); if ($file !== false) { while (($line = fgets($file)) !== false) { echo $line; } fclose($file); }
Common modes include r (read), w (write and truncate), a (append), and their + variants for reading and writing.
Check permissions and errors when handling files. Never allow arbitrary user input to determine sensitive filesystem paths.
19. Date and Time
echo date("Y-m-d"); echo date("H:i:s"); echo date("d-m-Y");
Set a timezone explicitly when required:
date_default_timezone_set("Asia/Kathmandu"); echo date("Y-m-d H:i:s");
Use DateTimeImmutable for more complex date calculations:
$date = new DateTimeImmutable("2026-01-01"); $nextWeek = $date->modify("+7 days"); echo $nextWeek->format("Y-m-d");
20. Object-Oriented Programming (OOP)
Class and Object
class Student { public string $name; public function __construct(string $name) { $this->name = $name; } public function introduce(): string { return "My name is " . $this->name; } } $student = new Student("Uday"); echo $student->introduce();
Access Modifiers
public: accessible from anywhere.protected: accessible in the class and subclasses.private: accessible only within the declaring class.
Inheritance
class Animal { public function sound(): string { return "Animal sound"; } } class Dog extends Animal { public function sound(): string { return "Bark"; } }
Abstract Classes
abstract class Shape { abstract public function area(): float; } class Square extends Shape { public function __construct( private float $side ) {} public function area(): float { return $this->side * $this->side; } }
Interfaces
interface Payment { public function pay(float $amount): bool; } class CashPayment implements Payment { public function pay(float $amount): bool { return true; } }
Traits
Traits provide reusable methods for classes.
trait Logger { public function log(string $message): void { echo $message; } } class App { use Logger; }
Static Members
class MathHelper { public static function square(int $n): int { return $n * $n; } } echo MathHelper::square(5);
21. Namespaces
Namespaces organize classes, functions, and constants and help prevent naming conflicts.
<?php namespace App\Services; class UserService { public function getName(): string { return "Uday"; } }
Import a class from another namespace:
use App\Services\UserService; $service = new UserService(); echo $service->getName();
A namespace declaration must appear at the beginning of the PHP file, apart from permitted declarations.
22. Error Handling and Exceptions
try, catch, and finally
try { throw new Exception("Something went wrong"); } catch (Exception $e) { echo $e->getMessage(); } finally { // Cleanup code }
Throwing an Exception
function divide(float $a, float $b): float { if ($b == 0.0) { throw new InvalidArgumentException( "Division by zero" ); } return $a / $b; }
Catch exceptions at an appropriate application boundary and log detailed errors securely. Avoid displaying stack traces or secrets to production users.
23. Sessions
Sessions maintain server-side information across requests.
session_start(); $_SESSION["username"] = "Uday"; echo $_SESSION["username"];
To remove a session variable:
unset($_SESSION["username"]);
To end a session:
$_SESSION = []; session_destroy();
Regenerate the session ID after authentication using session_regenerate_id(true). Configure secure cookie attributes and protect authenticated actions against CSRF.
24. Cookies
Cookies store small values in the user's browser.
setcookie("theme", "dark", [ "expires" => time() + 3600, "path" => "/", "secure" => true, "httponly" => true, "samesite" => "Lax" ]);
Read a cookie:
$theme = $_COOKIE["theme"] ?? "light";
Cookies must be set before output is sent. Use secure => true on HTTPS sites; cookie values must be treated as untrusted input.
25. Database Connectivity with PDO
PDO provides a consistent interface for accessing supported databases.
<?php $pdo = new PDO( "mysql:host=localhost;dbname=school;charset=utf8mb4", $dbUser, $dbPassword, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ] );
Store credentials in environment variables or a secure configuration system rather than committing them to source control.
Insert Data Safely
$stmt = $pdo->prepare( "INSERT INTO students (name, age) VALUES (?, ?)" ); $stmt->execute(["Uday", 23]);
Read Data
$stmt = $pdo->prepare( "SELECT id, name, age FROM students WHERE age > ?" ); $stmt->execute([18]); $students = $stmt->fetchAll(); foreach ($students as $student) { echo htmlspecialchars( $student["name"], ENT_QUOTES, "UTF-8" ); }
Update and Delete
$stmt = $pdo->prepare( "UPDATE students SET age = ? WHERE id = ?" ); $stmt->execute([24, 1]); $stmt = $pdo->prepare( "DELETE FROM students WHERE id = ?" ); $stmt->execute([1]);
Use prepared statements for values rather than concatenating user input into SQL queries. SQL identifiers, such as column names, require separate validation or allowlisting.
26. JSON Handling
Encode PHP Data as JSON
$user = [ "name" => "Uday", "age" => 23 ]; $json = json_encode($user, JSON_PRETTY_PRINT); echo $json;
Decode JSON
$data = json_decode( '{"name":"Uday","age":23}', true, 512, JSON_THROW_ON_ERROR ); echo $data["name"];
The second argument true requests associative arrays instead of objects.
27. Creating a Simple JSON API
<?php header("Content-Type: application/json; charset=utf-8"); $data = [ "success" => true, "message" => "Welcome to the PHP API", "version" => "1.0" ]; echo json_encode($data);
Use appropriate HTTP status codes, validate requests, and authenticate endpoints that access protected information.
28. Password Security
Never store plain-text passwords.
Hash a Password
$password = "example-password"; $hash = password_hash( $password, PASSWORD_DEFAULT );
Verify a Password
if (password_verify($password, $hash)) { echo "Password verified"; } else { echo "Invalid password"; }
Use password_needs_rehash() when appropriate to upgrade stored hashes as password hashing defaults change.
Authentication also requires rate limiting, secure session handling, and safe account recovery.
29. Security Essentials
Prevent SQL Injection
Use PDO prepared statements or equivalent parameterized queries.
Prevent Cross-Site Scripting (XSS)
Escape untrusted text for its output context, for example:
echo htmlspecialchars( $userInput, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8" );
Validate Input
$email = filter_input( INPUT_POST, "email", FILTER_VALIDATE_EMAIL ); if ($email === false || $email === null) { echo "Invalid email"; }
Prevent CSRF
For state-changing forms, generate a random token, store it in the session, include it in the form, and compare the submitted token using hash_equals().
Additional Practices
- Use HTTPS.
- Keep PHP and dependencies updated.
- Disable detailed error display in production.
- Apply least-privilege filesystem and database permissions.
- Validate uploaded files and enforce size limits.
- Avoid unsafe dynamic file inclusion.
- Never execute untrusted input as code.
- Restrict CORS origins where appropriate.
30. File Uploads
HTML form:
<form method="post" enctype="multipart/form-data"> <input type="file" name="document" required> <button type="submit">Upload</button> </form>
PHP handling example:
<?php if ( isset($_FILES["document"]) && $_FILES["document"]["error"] === UPLOAD_ERR_OK ) { $tmp = $_FILES["document"]["tmp_name"]; if (is_uploaded_file($tmp)) { $mime = (new finfo(FILEINFO_MIME_TYPE)) ->file($tmp); $allowed = [ "image/jpeg" => "jpg", "image/png" => "png" ]; if (isset($allowed[$mime])) { $filename = bin2hex(random_bytes(16)) . "." . $allowed[$mime]; $destination = __DIR__ . "/uploads/" . $filename; if (move_uploaded_file($tmp, $destination)) { echo "Upload successful"; } } } }
Create the uploads directory with appropriate permissions before using this example. Production upload handling should also enforce file-size limits, verify image contents where relevant, and prevent uploaded files from being executed.
31. Useful Built-in Functions
| Function | Purpose |
|---|---|
isset() | Checks whether a variable exists and is not null |
empty() | Checks whether a value is considered empty |
unset() | Removes a variable or array entry |
is_array() | Checks whether a value is an array |
is_string() | Checks whether a value is a string |
is_numeric() | Checks whether a value is numeric |
count() | Counts array elements |
explode() | Splits a string into an array |
implode() | Joins array elements into a string |
array_map() | Applies a callback to array elements |
array_filter() | Filters array elements |
array_reduce() | Reduces an array to one result |
in_array() | Checks whether a value exists in an array |
file_exists() | Checks whether a filesystem path exists |
is_readable() | Checks whether a path is readable |
random_int() | Generates a cryptographically secure random integer |
header() | Sends HTTP headers |
http_response_code() | Sets or reads the HTTP status code |
32. PHP with HTML
PHP can be embedded inside HTML.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>PHP Website</title> </head> <body> <h1> <?php echo "Welcome to Ugenz Academy"; ?> </h1> <p>Today is <?php echo date("Y-m-d"); ?></p> </body> </html>
Use <?= $value ?> as shorthand for <?php echo $value; ?>.
33. Composer and Dependency Management
Composer is PHP's dependency manager.
composer init composer require vendor/package composer install composer update composer remove vendor/package
Load Composer's autoloader:
require __DIR__ . "/vendor/autoload.php";
Commit composer.json and normally composer.lock for reproducible dependency installation. Review dependency changes before updating production applications.
34. Useful PHP Commands
php -v php --ini php -m php -l index.php php index.php php -S localhost:8000 composer --version composer install
php -v: shows the installed PHP version.php --ini: shows configuration file information.php -m: lists loaded extensions.php -l: checks syntax without executing the file.php -S: starts the built-in development server.
The built-in server is intended for development, not public production hosting.
35. Modern PHP Features
| Feature | Introduced |
|---|---|
| Anonymous functions | PHP 5.3 |
| Traits | PHP 5.4 |
| Return types | PHP 7.0 |
Null coalescing ?? | PHP 7.0 |
| Nullable types | PHP 7.1 |
| Typed properties | PHP 7.4 |
| Arrow functions | PHP 7.4 |
| Union types | PHP 8.0 |
| Named arguments | PHP 8.0 |
| Attributes | PHP 8.0 |
| Constructor property promotion | PHP 8.0 |
match expression | PHP 8.0 |
| Enums | PHP 8.1 |
| Readonly properties | PHP 8.1 |
| Fibers | PHP 8.1 |
| Readonly classes | PHP 8.2 |
| Typed class constants | PHP 8.3 |
| Property hooks | PHP 8.4 |
Always check the PHP version deployed on your server before using version-specific syntax. Use a currently supported PHP release and review its official migration documentation.
36. Quick Reference
<?php // Variables $name = "Uday"; $age = 23; // Output echo "Hello, $name"; // Input from request $value = $_GET["value"] ?? ""; // Condition if ($age >= 18) { echo "Adult"; } // Loop for ($i = 1; $i <= 3; $i++) { echo $i; } // Array $numbers = [10, 20, 30]; // Function function add(int $a, int $b): int { return $a + $b; } // JSON echo json_encode(["success" => true]); // Class class User { public function greet(): string { return "Hello"; } } $user = new User(); echo $user->greet(); ?>
37. Official Resources
- PHP documentation: https://www.php.net/docs.php
- PHP language reference: https://www.php.net/manual/en/langref.php
- PHP function reference: https://www.php.net/manual/en/funcref.php
- PDO documentation: https://www.php.net/manual/en/book.pdo.php
- Composer documentation: https://getcomposer.org/doc/
- PHP supported versions: https://www.php.net/supported-versions.php
Key takeaway: PHP is a server-side language that combines programming logic, HTML, database operations, file handling, and web security to build dynamic websites and APIs. Learn the syntax and core concepts first, then practice forms, databases, OOP, APIs, and secure authentication to build complete applications.