PHP: Server-Side Scripting

Master the language that powers 77% of websites.

// PHP HISTORY

Created by Rasmus Lerdorf in 1994, PHP (Hypertext Preprocessor) started as a set of Common Gateway Interface (CGI) binaries written in C. Today, it powers WordPress, Laravel, Drupal, and millions of dynamic websites worldwide.

// WHY PHP MATTERS

PHP is the backbone of the modern web. It seamlessly integrates with HTML, connects to databases, handles form data, and creates dynamic content. With PHP 8's modern features like JIT compilation and attributes, it's more powerful than ever.

Start Learning →

// Lessons

12 lessons • Server-side mastery

LESSON 01

Introduction to PHP

Server-side scripting for web development

Beginner
LESSON 02

Variables & Data Types

Store and manipulate data values

Beginner
LESSON 03

Operators & Expressions

Perform calculations and comparisons

Beginner
LESSON 04

Control Flow - Conditionals

Make decisions with if/else statements

Beginner
LESSON 05

Arrays in PHP

Work with indexed and associative arrays

Beginner
LESSON 06

Working with Strings

Manipulate text with built-in functions

Beginner
LESSON 07

Forms & User Input

Handle GET and POST data securely

Intermediate
LESSON 08

Sessions & Cookies

Maintain state across page requests

Intermediate
LESSON 09

Database Integration

Connect to MySQL with PDO.

Intermediate
LESSON 10

File Handling

Read, write, and upload files.

Intermediate
LESSON 11

Object-Oriented PHP

Classes, objects, and inheritance.

Advanced
LESSON 12

Security & Best Practices

Prevent XSS, SQL injection, hash passwords.

Advanced

// Why PHP

PHP was created by Rasmus Lerdorf in 1994 as a set of CGI binaries written in C. Today, it powers 77% of all websites with known server-side programming, including WordPress, Facebook, and Wikipedia.

PHP is the backbone of the modern web. It seamlessly integrates with HTML, connects to databases, handles form data, and creates dynamic content. With PHP 8's modern features like JIT compilation and attributes, it's more powerful than ever.

From small personal blogs to enterprise-scale applications, PHP scales to meet your needs. The massive ecosystem of frameworks like Laravel, Symfony, and CodeIgniter makes rapid development a reality.

The web runs on PHP. Own it.

// Tools & References

📖 Official Docs

PHP Documentation

php.net

⚙️ PHP Manual

Function Reference

php.net/manual

🎓 Laracasts

Video Tutorials

laracasts.com

📦 Packagist

PHP Package Repository

packagist.org

// Introduction to PHP

×

What is PHP?

PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed specifically for web development. It runs on the server, generating HTML that is sent to the client.

Why PHP?

  • Server-side: Code runs on server, hidden from users
  • Database Integration: Native support for MySQL, PostgreSQL, and more
  • Embeddable: Mixes easily with HTML
  • Cross-platform: Runs on Windows, Linux, macOS
  • Open Source: Free to use with massive community
PHP FACTS: PHP powers 77% of all websites with known server-side programming language. WordPress, Facebook, and Wikipedia all use PHP.

Your First PHP Script

// This is a PHP comment echo "Hello, World!"; ?>

PHP Tags

PHP code must be enclosed in opening and closing tags:

// Standard PHP tags (recommended) ... ?> // Short echo tags (requires short_open_tag enabled) "Hello"; ?> // ASP-style tags (deprecated) <% ... %>

PHP Configuration

$ php --version PHP 8.2.0 (cli) (built: Dec 7 2022 10:30:00) $ php -i | head -20 phpinfo()

Quiz

1. PHP stands for _____ Preprocessor.

Hint: H-T-M-L related

2. PHP runs on the _____.

Hint: Not client

3. echo is a PHP _____.

Hint: Not a function

4. The opening PHP tag is _____.

Hint: Three characters

5. PHP is _____ source.

Hint: Free to use

6. WordPress uses PHP as its _____.

Hint: Programming language

7. PHP code ends with _____.

Hint: Two characters

8. php --_____ shows version info.

Hint: Command line

Show Answers

Answers

  1. hypertext
  2. server
  3. language construct
  4. open
  5. language
  6. ?>
  7. version

// Variables & Data Types

×

Variables in PHP

Variables in PHP start with a dollar sign ($) followed by the variable name. Variables are case-sensitive.

// Creating variables $name = "Alice"; $age = 25; $height = 5.8; $isStudent = true; echo $name;

Data Types

Strings

$single = 'Hello'; $double = "Hello, $name"; $heredoc = <<

Numbers

$integer = 42; $float = 3.14; $scientific = 1.5e3; // 1500

Booleans

$isActive = true; $isDeleted = false;

Type Checking

$x = 10; echo gettype($x); // integer $y = "Hello"; echo gettype($y); // string

Type Conversion

// Type casting $x = (int)"10"; $y = (string)42; $z = (bool)"non-empty"; // Or using settype() $num = "3.14"; settype($num, "float");

Variable Variables

PHP supports variable variables - using one variable's value as another variable's name:

$foo = "bar"; $$foo = "Hello"; echo $bar; // Hello

Quiz

1. Variables start with _____.

Hint: Dollar sign

2. Strings can use _____ quotes.

Hint:

3. gettype() returns the _____.

Hint: Type of variable

4. (int) casts to _____.

Hint: Whole number

5. $$foo is a _____ variable.

Hint: Dynamic name

6. Heredoc creates _____ strings.

Hint: Multiple lines

7. true and false are _____ values.

Hint: True/False

8. PHP is _____ typed.

Hint: No declaration

Show Answers

Answers

  1. $
  2. single or double
  3. data type
  4. integer
  5. variable
  6. multi-line
  7. boolean
  8. dynamically

// Operators & Expressions

×

Arithmetic Operators

$a = 10; $b = 3; echo $a + $b; // 13 Addition echo $a - $b; // 7 Subtraction echo $a * $b; // 30 Multiplication echo $a / $b; // 3.33 Division echo $a % $b; // 1 Modulus echo $a ** $b; // 1000 Exponentiation

Assignment Operators

$x = 10; $x += 5; // $x = 15 $x -= 3; // $x = 12 $x *= 2; // $x = 24 $x /= 4; // $x = 6 $x %= 5; // $x = 1 // String operators $str = "Hello"; $str .= " World"; // $str = "Hello World"

Comparison Operators

$a = 10; $b = 20; $c = "10"; echo $a == $c; // true (equal value) echo $a === $c; // false (identical type) echo $a != $b; // true (not equal) echo $a <> $b; // true (not equal) echo $a !== // true (not identical) echo $a < $b; // true (less than) echo $a > $b; // false (greater than) echo $a <= $b; // true (less or equal)

Spaceship Operator (PHP 7+)

Returns -1, 0, or 1 depending on comparison:

echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1

Logical Operators

// and / && - True if both are true // or / || - True if either is true // xor - True if one is true, not both // ! - Negation $age = 25; if ($age >= 18 && $age <= 65) { echo "Working age"; }

Quiz

1. % returns _____.

Hint: Modulus

2. == checks _____.

Hint: Equal value

3. === checks _____.

Hint: Same type

4. && means _____.

Hint: Both true

5. != means _____.

Hint: Different

6. <=> is the _____ operator.

Hint: PHP 7+

7. .= is _____ concatenation.

Hint: Append

8. ! is the _____ operator.

Hint: Not

Show Answers

Answers

  1. remainder
  2. equality
  3. identity
  4. and
  5. not equal
  6. spaceship
  7. assignment
  8. negation

// Control Flow - Conditionals

×

If/Else Statements

The foundation of decision-making in PHP. Use if/else to execute code based on conditions.

$age = 25; if ($age >= 18) { echo "Adult"; } else { echo "Minor"; }
BRACE STYLE: Always use curly braces {} even for single-line statements. This prevents errors when adding more code later.

Elseif Chains

Handle multiple conditions with elseif. PHP evaluates conditions top-to-bottom and stops at the first match.

$score = 85; if ($score >= 90) { echo "A"; } elseif ($score >= 80) { echo "B"; } elseif ($score >= 70) { echo "C"; } else { echo "F"; }

Switch Statements

Use switch when comparing one variable against many possible values. Cleaner than long elseif chains for equality checks.

$day = "Monday"; switch ($day) { case "Monday": echo "Start of week"; break; case "Friday": echo "Weekend is near"; break; default: echo "Regular day"; }
DON'T FORGET BREAK: Without break, PHP will fall through to the next case. This can cause unexpected behavior.

Ternary Operator

A shorthand for simple if/else statements. Use for simple assignments, not complex logic.

$status = ($age >= 18) ? "adult" : "minor"; // Nested ternary (use sparingly) $label = ($age < 13) ? "child" : (($age < 20) ? "teen" : "adult");

Null Coalescing Operator (??)

PHP 7+ introduced ?? to handle null values gracefully. Returns the first non-null value.

// Instead of isset() checks $username = $_GET['user'] ?? 'Guest'; // Chaining multiple values $value = $a ?? $b ?? $c ?? 'default';

Match Expressions (PHP 8+)

The modern replacement for switch. Match returns a value and uses strict comparison (===) by default.

$grade = match ($score) { 90, 95, 100 => 'A', 80 .. 89 => 'B', 70 .. 79 => 'C', default => 'F' };
MATCH BENEFITS: Match expressions return values, use strict comparison, and don't require break statements. The result can be assigned directly to a variable.

Quiz

1. elseif handles _____ conditions.

Hint: More than one

2. switch compares for _____.

Hint: Same value

3. ?? is the _____ operator.

Hint: Null fallback

4. match was added in PHP _____.

Hint: Version number

Show Answers

Answers

  1. multiple
  2. equality
  3. null coalescing
  4. 8

// Arrays in PHP

×

Indexed Arrays

Indexed arrays use numeric keys starting from 0. PHP 5.4+ introduced the short array syntax [] which is the preferred modern approach.

// Modern short syntax (recommended) $fruits = ["Apple", "Banana", "Cherry"]; // Legacy array() function $colors = array("Red", "Green", "Blue"); // Access elements echo $fruits[0]; // Apple $fruits[] = "Orange"; // Append to end
ARRAY TIP: Array indices start at 0, not 1. The first element is always at index 0.

Associative Arrays

Associative arrays use named keys instead of numeric indices, making them perfect for storing structured data like user profiles.

$user = [ "name" => "Alice", "email" => "alice@example.com", "age" => 25, "active" => true ]; echo $user["name"]; // Alice $user["city"] = "New York"; // Add new key

Multidimensional Arrays

Arrays can contain other arrays, creating nested structures for complex data like tables or matrices.

$matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; echo $matrix[1][2]; // 6 $users = [ ["id" => 1, "name" => "Alice"], ["id" => 2, "name" => "Bob"] ];

Array Functions

PHP provides over 80 array functions. Here are the most essential ones for everyday development.

$arr = [3, 1, 4, 1, 5]; count($arr); // 5 - Count elements sort($arr); // Sort ascending (modifies original) rsort($arr); // Sort descending in_array(4, $arr); // true - Check existence array_search(4, $arr); // 2 - Find key of value array_merge($a, $b); // Combine arrays array_slice($arr, 1, 3); // Extract portion

Array Iteration

// foreach - The preferred way foreach ($fruits as $fruit) { echo $fruit . "\n"; } // With keys foreach ($user as $key => $value) { echo "$key: $value\n"; } // Array map for transformation $upper = array_map(fn($f) => strtoupper($f), $fruits);
PERFORMANCE TIP: foreach is significantly faster than for loops for arrays. Always prefer foreach unless you specifically need the index.

Quiz

1. Array indices start at _____.

Hint: First position

2. Arrays with named keys are called _____ arrays.

Hint: Key-value pairs

3. _____() returns the number of elements.

Hint: Array size

4. _____ is the preferred loop for arrays.

Hint: For each element

Show All Answers

Answers

  1. 0
  2. associative
  3. count
  4. foreach

// Working with Strings

×

String Basics

PHP offers multiple ways to define strings, each with different behavior regarding variable interpolation and escaping.

// Single quotes - literal, no variable interpolation $name = 'Alice'; echo 'Hello $name'; // Hello $name // Double quotes - variables are interpolated echo "Hello $name"; // Hello Alice echo "Sum: {2 + 3}"; // Sum: 5 // Heredoc syntax for multi-line strings $text = <<

Common String Functions

PHP has over 100 string functions. Master these essential ones first.

$str = " Hello World "; strlen($str); // 15 - String length trim($str); // "Hello World" - Remove whitespace strtolower($str); // " hello world " strtoupper($str); // " HELLO WORLD " ucfirst("hello"); // "Hello" ucwords("hello world"); // "Hello World"

String Manipulation

$str = "Hello World"; // Find and replace str_replace("World", "PHP", $str); // "Hello PHP" // Substring extraction substr($str, 0, 5); // "Hello" substr($str, 6); // "World" // String position strpos($str, "World"); // 6 strpos($str, "xyz"); // false // String splitting explode(" ", $str); // ["Hello", "World"] implode("-", ["a", "b"]); // "a-b"
STRING SAFETY: Always use === when checking strpos results. strpos returns 0 if found at start, which is falsy. Use `strpos($str, "x") === false` to check for "not found".

Regular Expressions (Regex)

Regex allows pattern matching for complex string validation and manipulation.

// preg_match - Check if pattern matches $email = "user@example.com"; $pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/"; preg_match($pattern, $email); // 1 (matches) // preg_replace - Replace using pattern $text = "Phone: 123-456-7890"; $clean = preg_replace("/\D/", "", $text); // "1234567890" // preg_split - Split by pattern $words = preg_split("/\s+/", "Hello World"); // ["Hello", "World"]

String Formatting

// sprintf for formatted output $price = sprintf("$%.2f", 19.99); // "$19.99" // Number formatting number_format(1234567.89, 2); // "1,234,567.89" // Modern string interpolation (PHP 8.2+) $name = "Alice"; echo "Hello {$name}!"; // Hello Alice!

Quiz

1. _____ quotes interpolate variables in strings.

Hint: " vs '

2. _____() returns string length.

Hint: String length function

3. _____ matches regex patterns.

Hint: PREG function

4. _____() splits a string into an array.

Hint: String to array

Show All Answers

Answers

  1. double
  2. strlen
  3. preg_match
  4. explode

// Forms & User Input

×

GET vs POST Methods

Understanding when to use each HTTP method is crucial for secure and functional web applications.

// GET - For retrieval, data in URL (limit ~2048 chars) // Visible in URL, bookmarkable, cacheable $search = $_GET['q'] ?? ""; // POST - For creation/updates, data in request body // Not visible in URL, no size limit, not cacheable $email = $_POST['email'] ?? ""; // $_REQUEST contains both GET and POST $value = $_REQUEST['field']; // Prefer specific superglobals
SECURITY RULE: Never use GET for sensitive data (passwords, credit cards) or actions that modify data. Always use POST for forms that change state.

Form Validation

Always validate user input before processing. Never trust data from the client.

if ($_SERVER["REQUEST_METHOD"] === "POST") { $errors = []; // Required field check if (empty($_POST['name'])) { $errors[] = "Name is required"; } // Email validation if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format"; } // Length validation if (strlen($_POST['password']) < 8) { $errors[] = "Password must be at least 8 characters"; } if (empty($errors)) { // Process form... } }

Input Sanitization

Remove potentially harmful characters while preserving valid data.

// FILTER_SANITIZE_STRING - Remove tags, encode special chars $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS); // FILTER_VALIDATE_INT - Returns int or false $age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT); // FILTER_VALIDATE_URL $website = filter_input(INPUT_POST, 'website', FILTER_VALIDATE_URL); // FILTER_VALIDATE_IP $ip = filter_input(INPUT_POST, 'ip', FILTER_VALIDATE_IP);

CSRF Protection

Cross-Site Request Forgery attacks trick users into performing unwanted actions. Protect your forms with tokens.

// 1. Generate and store CSRF token session_start(); if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } $token = $_SESSION['csrf_token']; // 2. Include in form // // 3. Validate on submission if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die("CSRF token validation failed"); }
CRITICAL: Always use hash_equals() for token comparison, not == or ===. This prevents timing attacks that could reveal your token.

File Uploads

// Validate file upload if (isset($_FILES['avatar'])) { $file = $_FILES['avatar']; // Check for upload errors if ($file['error'] !== UPLOAD_ERR_OK) { die("Upload failed"); } // Validate file type $allowed = ['image/jpeg', 'image/png', 'image/gif']; if (!in_array($file['type'], $allowed)) { die("Invalid file type"); } // Move to permanent location $dest = 'uploads/' . basename($file['name']); move_uploaded_file($file['tmp_name'], $dest); }

Quiz

1. Use _____ for form submissions that change data.

Hint: Not GET

2. _____() validates and sanitizes input.

Hint: FILTER_VALIDATE

3. _____ tokens prevent cross-site request forgery.

Hint: Cross-site protection

4. _____() compares strings securely against timing attacks.

Hint: Secure comparison

Show All Answers

Answers

  1. post
  2. filter_var
  3. csrf
  4. hash_equals

// Sessions & Cookies

×

Session Management

Sessions allow you to store user data across multiple page requests. The session ID is typically stored in a cookie.

// MUST be called before any output session_start(); // Store data in session $_SESSION['user_id'] = 123; $_SESSION['username'] = "alice"; $_SESSION['role'] = "admin"; // Access session data echo "Welcome, " . $_SESSION['username']; // Check if logged in if (isset($_SESSION['user_id'])) { echo "User is authenticated"; }
CRITICAL: session_start() must be called before ANY output - including whitespace, HTML, or BOM characters. Put it at the very top of your PHP files.

Session Security

Secure your sessions against hijacking and fixation attacks.

// Regenerate session ID after login session_regenerate_id(true); // Configure secure session settings ini_set('session.cookie_httponly', 1); ini_set('session.cookie_secure', 1); // HTTPS only ini_set('session.use_strict_mode', 1); ini_set('session.cookie_samesite', 'Strict'); // Destroy session completely session_destroy(); // Removes server data setcookie(session_name(), '', 1); // Clear cookie

Cookies

Cookies store data on the client's browser. They're sent with every request to your domain.

// Set a cookie (expires in 30 days) setcookie( 'theme', // Name 'dark', // Value [ 'expires' => time() + (86400 * 30), 'path' => '/', 'secure' => true, // HTTPS only 'httponly' => true, // Not accessible via JS 'samesite' => 'Strict' // CSRF protection ] ); // Read cookie $theme = $_COOKIE['theme'] ?? 'light'; // Delete cookie setcookie('theme', '', ['expires' => 1]);

Authentication Example

function login($user) { session_start(); session_regenerate_id(true); // Prevent fixation $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['username']; $_SESSION['logged_in'] = true; } function requireAuth() { session_start(); if (empty($_SESSION['logged_in'])) { header('Location: /login.php'); exit; } } function logout() { session_start(); session_destroy(); setcookie(session_name(), '', 1); header('Location: /'); exit; }
SESSION LIFECYCLE: Session data persists until the browser is closed (session cookie) or until session.gc_maxlifetime expires (default 24 minutes of inactivity).

Quiz

1. _____() initializes a new session.

Hint: Required first

2. _____ cookies prevent JavaScript access.

Hint: XSS protection

3. session_regenerate_id() prevents session _____.

Hint: Fixation attack

4. Session data is stored on the _____.

Hint: Not client

Show All Answers

Answers

  1. session_start
  2. httponly
  3. regenerate
  4. server

// Database Integration

×

PDO: PHP Data Objects

PDO provides a consistent interface for accessing databases. It supports multiple database backends and is the recommended approach for modern PHP applications.

try { $pdo = new PDO( 'mysql:host=localhost;dbname=mydb;charset=utf8mb4', 'username', 'password', [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false ] ); } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); }
SECURITY FIRST: Always set ATTR_EMULATE_PREPARES to false for MySQL. This ensures real prepared statements are used, preventing SQL injection completely.

Prepared Statements

Prepared statements separate SQL code from data, making SQL injection impossible. This is mandatory for any database interaction with user input.

// SELECT with named parameters $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute([':id' => $userId]); $user = $stmt->fetch(); // INSERT with positional parameters $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)'); $stmt->execute([$name, $email]); $newId = $pdo->lastInsertId(); // UPDATE $stmt = $pdo->prepare('UPDATE users SET name = :name WHERE id = :id'); $stmt->execute([':name' => $name, ':id' => $id]);

CRUD Operations

// CREATE $stmt = $pdo->prepare('INSERT INTO posts (title, content) VALUES (:title, :content)'); $stmt->execute([':title' => $title, ':content' => $content]); // READ (fetch multiple) $stmt = $pdo->query('SELECT * FROM users WHERE active = 1'); $users = $stmt->fetchAll(); // READ (single) $stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([$id]); $user = $stmt->fetch(); // UPDATE $stmt = $pdo->prepare('UPDATE users SET last_login = NOW() WHERE id = ?'); $stmt->execute([$id]); // DELETE $stmt = $pdo->prepare('DELETE FROM users WHERE id = ?'); $stmt->execute([$id]);

Transactions

Transactions ensure multiple operations complete together or not at all - maintaining data integrity.

try { $pdo->beginTransaction(); // Deduct from sender $stmt = $pdo->prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?'); $stmt->execute([$amount, $fromId]); // Add to receiver $stmt = $pdo->prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?'); $stmt->execute([$amount, $toId]); // Record transaction $stmt = $pdo->prepare('INSERT INTO transactions (from_id, to_id, amount) VALUES (?, ?, ?)'); $stmt->execute([$fromId, $toId, $amount]); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); throw $e; }
ACID PROPERTIES: Transactions ensure Atomicity (all or nothing), Consistency, Isolation, and Durability. Essential for financial operations and data integrity.

Quiz

1. _____ is the recommended database interface in PHP.

Hint: PHP Data Objects

2. _____() creates a prepared statement.

Hint: Prevents SQL injection

3. A _____ ensures multiple operations complete together.

Hint: beginTransaction()

4. Prepared statements prevent _____ attacks.

Hint: Database security threat

Show All Answers

Answers

  1. pdo
  2. prepare
  3. transaction
  4. sql injection

// File Handling

×

Reading Files

PHP offers multiple ways to read file contents, from simple one-liners to resource-based approaches for large files.

// Read entire file (small files only) $content = file_get_contents('data.txt'); // Read into array (each line as element) $lines = file('data.txt', FILE_IGNORE_NEW_LINES); // Read CSV file $handle = fopen('users.csv', 'r'); while (($data = fgetcsv($handle)) !== false) { print_r($data); // Array of CSV columns } fclose($handle); // Memory-efficient for large files $handle = fopen('large.txt', 'r'); while (!feof($handle)) { $line = fgets($handle); // Process line by line... } fclose($handle);

Writing Files

// Write entire file (overwrites existing) file_put_contents('output.txt', 'Hello World'); // Append mode (create if doesn't exist) file_put_contents('log.txt', "New entry\n", FILE_APPEND); // Using file handle for more control $handle = fopen('output.txt', 'w'); fwrite($handle, 'Line 1\n'); fwrite($handle, 'Line 2\n'); fclose($handle); // Write CSV $handle = fopen('output.csv', 'w'); fputcsv($handle, ['Name', 'Email', 'Age']); // Header fputcsv($handle, ['Alice', 'alice@example.com', 25]); fclose($handle);
FILE MODES: 'r' = read, 'w' = write (truncate), 'a' = append, 'x' = create only (fail if exists), 'r+' = read+write. Always close handles with fclose().

File Uploads

Secure file uploads require validation at every step. Never trust the filename or type provided by the client.

if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_FILES['document'])) { $file = $_FILES['document']; // Check for upload errors if ($file['error'] !== UPLOAD_ERR_OK) { die("Upload error: " . $file['error']); } // Validate file size (max 5MB) if ($file['size'] > 5 * 1024 * 1024) { die("File too large"); } // Validate MIME type (don't trust extension) $finfo = new finfo(FILEINFO_MIME_TYPE); $mime = $finfo->file($file['tmp_name']); $allowed = ['application/pdf', 'image/jpeg', 'image/png']; if (!in_array($mime, $allowed)) { die("Invalid file type"); } // Generate safe filename $ext = pathinfo($file['name'], PATHINFO_EXTENSION); $newName = uniqid() . '.' . $ext; $dest = 'uploads/' . $newName; // Move file (only use this function!) if (move_uploaded_file($file['tmp_name'], $dest)) { echo "Upload successful: $newName"; } } }

JSON Handling

// Decode JSON to array $json = '{"name":"Alice","age":25}'; $data = json_decode($json, true); // true = associative array echo $data['name']; // Alice // Encode array to JSON $user = ['name' => 'Bob', 'email' => 'bob@example.com']; $json = json_encode($user); echo $json; // {"name":"Bob","email":"bob@example.com"} // Check for JSON errors if (json_last_error() !== JSON_ERROR_NONE) { echo "JSON error: " . json_last_error_msg(); }
UPLOAD SECURITY: Always use finfo for MIME validation, never trust $_FILES['type']. Store files outside web root when possible. Never execute uploaded files.

Quiz

1. _____() reads an entire file.

Hint: Simple file read

2. _____() is the safe way to move uploaded files.

Hint: Upload security function

3. _____() converts JSON to PHP arrays.

Hint: JSON parsing

4. _____ validates actual file MIME types securely.

Hint: File info class

Show All Answers

Answers

  1. file_get_contents
  2. move_uploaded_file
  3. json_decode
  4. finfo

// Object-Oriented PHP

×

Classes and Objects

Object-Oriented Programming (OOP) allows you to organize code into reusable, self-contained objects with properties and methods.

class Car { // Properties public $brand; public $model; private $speed = 0; // Constructor public function __construct($brand, $model) { $this->brand = $brand; $this->model = $model; } // Methods public function accelerate($amount) { $this->speed += $amount; return $this; } public function getSpeed() { return $this->speed; } } // Create object $myCar = new Car('Toyota', 'Corolla'); $myCar->accelerate(30); echo $myCar->getSpeed(); // 30

Visibility Modifiers

Control access to class members with public, protected, and private visibility.

class BankAccount { public $owner; // Accessible anywhere protected $balance; // Class + subclasses private $pin; // This class only public function deposit($amount) { $this->balance += $amount; } private function validatePin($pin) { return $this->pin === $pin; } }
ENCAPSULATION: Always make properties private or protected. Use public getter/setter methods to control access. This protects object integrity and allows validation.

Inheritance

Child classes inherit properties and methods from parent classes, promoting code reuse.

class Animal { protected $name; public function __construct($name) { $this->name = $name; } public function speak() { return "Some sound"; } } class Dog extends Animal { public function speak() { return "Woof! My name is " . $this->name; } public function fetch() { return "Fetching the ball!"; } } $dog = new Dog('Buddy'); echo $dog->speak(); // Woof! My name is Buddy

Static Methods and Properties

Static members belong to the class itself, not to instances. Useful for utility functions and shared state.

class Database { private static $instance = null; private $connection; public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } private function __construct() { $this->connection = new PDO(...); } } // Usage - Singleton pattern $db = Database::getInstance();

Autoloading with PSR-4

PSR-4 is the modern standard for autoloading classes from file paths based on namespaces.

// composer.json { "autoload": { "psr-4": { "App\\": "src/" } } } // src/Controller/UserController.php namespace App\Controller; class UserController { // Automatically loaded from src/Controller/UserController.php } // Usage require 'vendor/autoload.php'; $controller = new App\Controller\UserController();

Quiz

1. A _____ is a blueprint for creating objects.

Hint: OOP blueprint

2. _____ visibility restricts access to the defining class only.

Hint: Most restrictive

3. The _____ keyword creates inheritance.

Hint: Parent-child relationship

4. _____ is the autoloading standard.

Hint: PHP-FIG standard

Show All Answers

Answers

  1. class
  2. private
  3. extends
  4. psr-4

// Security & Best Practices

×

XSS Prevention

Cross-Site Scripting (XSS) attacks inject malicious scripts into your pages. Always escape output when displaying user data.

// NEVER do this - vulnerable to XSS echo $_GET['name']; // ALWAYS escape output echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8'); // Short helper function function e($string) { return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } // Usage echo e($userInput); // For JavaScript context (additional escaping) echo json_encode($userInput, JSON_HEX_TAG | JSON_HEX_AMP);
XSS RULE: Escape ALL output. Use htmlspecialchars() for HTML, json_encode() for JavaScript, urlencode() for URLs. Assume all user input is malicious.

SQL Injection Prevention

SQL injection is one of the most dangerous vulnerabilities. Prepared statements are the only reliable defense.

// NEVER concatenate user input (VULNERABLE!) $query = "SELECT * FROM users WHERE id = '$id'"; // ALWAYS use prepared statements $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute([':id' => $id]); // Additional: Input validation $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); if ($id === false) { die("Invalid ID"); }

Password Hashing

Never store passwords in plain text. PHP provides secure hashing functions that handle salt and iteration automatically.

// Hash password (during registration) $password = $_POST['password']; $hash = password_hash($password, PASSWORD_DEFAULT); // Store $hash in database // Verify password (during login) if (password_verify($inputPassword, $storedHash)) { // Password matches - login successful } else { // Invalid password } // Check if hash needs rehashing (algorithm updated) if (password_needs_rehash($storedHash, PASSWORD_DEFAULT)) { $newHash = password_hash($inputPassword, PASSWORD_DEFAULT); // Update database with new hash }

Composer Dependency Management

Composer is PHP's standard dependency manager. Never reinvent the wheel - use well-tested libraries.

// composer.json - Define dependencies { "name": "mycompany/project", "require": { "php": ">=8.1", "vlucas/phpdotenv": "^5.0", "firebase/php-jwt": "^6.0" }, "require-dev": { "phpunit/phpunit": "^10.0" }, "autoload": { "psr-4": { "App\\": "src/" } } } // Terminal commands composer install // Install dependencies composer update // Update to latest versions composer require vendor/package // Add new package

PSR Standards

PHP-FIG PSR standards ensure code interoperability across frameworks and libraries.

// PSR-1: Basic Coding Standard - Use - Files should declare symbols OR execute logic, not both - Namespaces and classes follow autoloading (PSR-4) // PSR-12: Extended Coding Style - 4 spaces for indentation (no tabs) - Opening braces on same line for classes/methods - One statement per line - Use elseif not else if // PSR-3: Logger Interface use Psr\Log\LoggerInterface; class MyService { public function __construct( private LoggerInterface $logger ) {} public function doWork() { $this->logger->info('Work completed'); } }
SECURITY CHECKLIST: 1) Use prepared statements for all SQL. 2) Escape all output with htmlspecialchars(). 3) Use password_hash() for passwords. 4) Validate and sanitize all input. 5) Keep dependencies updated with Composer.

Quiz

1. _____() prevents XSS when outputting user data.

Hint: Escape HTML entities

2. _____() securely hashes passwords.

Hint: bcrypt by default

3. _____ is PHP's dependency manager.

Hint: Package management

4. _____ statements prevent SQL injection.

Hint: PDO prepare()

Show All Answers

Answers

  1. htmlspecialchars
  2. password_hash
  3. composer
  4. prepared