Handle web requests and generate responses using server-side PHP code.
Before starting: HTML forms, HTTP requests, and a local PHP environment.
Practice project: Build a server-rendered reminder form with input validation and encoded output.
1. PHP Basics & Architecture
- PHP Introduction, Web Architecture & Zend Engine Execution Lifecycle
- Environment Setup: Apache, PHP 8.x, MySQL, php.ini & XAMPP
Read the example and try it
Run the page with your local PHP interpreter. A web request usually reports a different interface from a terminal run.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php echo PHP_SAPI, PHP_EOL, PHP_VERSION;Inspect the memory limit from the same web runtime that serves a page.
Serve a PHP file through localhost that echoes ini_get('memory_limit').
Expected result
A setting such as 128M or -1 is displayed. Compare it with the active web configuration; a CLI setting can differ. - Syntax Overview: Canonical Tags, Semicolons & HTML Embedding
Read the example and try it
A PHP expression can supply part of a page. The visitor receives the computed value inside the paragraph.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $seats = 4; ?><p>Free seats: <?= $seats ?></p>Write a small PHP-only file and print one line.
Use one PHP-only file with a single echo statement.
Expected result
Lab open - Variable Types, Scopes: Local, Global, Static & Dynamic ($$)
Read the example and try it
A static local keeps its value across calls in the same script execution. Each call increases this counter by one.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php function ticket() { static $last = 0; return ++$last; } echo ticket(), " ", ticket();Use the same variable name inside and outside a function.
Set $name to Hall outside a function and to Lab inside it. Print inside, then outside.
Expected result
Lab Hall - Constants & Magic Constants: define(), const and __DIR__, __FILE__
Read the example and try it
Use a constant for a limit shared by several calculations. Printing it does not require a dollar sign.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php const ROOM_LIMIT = 14; echo ROOM_LIMIT - 6;Build an include path relative to the current source file.
Build a path to settings.php in the running script's directory.
Expected result
Its directory matches __DIR__ and its basename is settings.php. The absolute prefix varies by machine.
2. Operators & Expressions
- Arithmetic & Assignment Operators: Exponentiation, Modulo & Shorthands
Read the example and try it
Use integer division for sealed packs and the remainder for loose cards. Both answers come from the same total.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $cards = 29; echo intdiv($cards, 6), " packs, ", $cards % 6, " loose";Compare numeric addition with string concatenation.
Start with integer 7 and integer 3.
Expected result
10 73 — addition then concatenation. - Comparison & Spaceship (<=>) Operators: Strict vs Loose Equality
Read the example and try it
Strict comparison distinguishes a number from text containing its digits. Compare both results before accepting a form value.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php var_dump("7" == 7, "7" === 7);Compare 3 and the string '3' using strict equality.
Compare integer 3 with text "3" using ===.
Expected result
false - Logical, Ternary (?:) & Null Coalescing (??, ??=) Operators
Read the example and try it
A default is used only when the key is absent or null. A deliberately empty label stays empty.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $filters = ["room" => ""]; var_export([$filters["room"] ?? "Lab", $filters["day"] ?? "Mon"]);Try a missing key, zero and an empty string with a fallback.
Use fallback 5 for a missing key, a stored zero and an empty string. Print JSON.
Expected result
[5,0,""] - Type Juggling, Strict Types (declare) & Explicit Casting
Read the example and try it
A cast can throw away information. Observe the fraction before using a converted number as a seat count.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $requested = "4.75"; echo (float)$requested, " becomes ", (int)$requested;Compare an explicit integer check with a cast for invalid input.
Use the input "3seats".
Expected result
The plain int cast returns 3. FILTER_VALIDATE_INT rejects the full input and returns false. - Operator Precedence & Short-Circuit Evaluation: and vs &&, or vs ||
Read the example and try it
Assignment and logical operators can group differently. Parentheses show which decision is being stored.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $open = true; $hasSeat = false; $canBook = ($open && $hasSeat); var_dump($canBook);Compare (2+3)*4 with 2+3*4.
Calculate both expressions using integer operands.
Expected result
20 14
3. Decision Making & Loops
- Conditional Branching: if, else, elseif & Alternative Syntax
Read the example and try it
Choose the first branch whose condition holds. Change the count to zero to exercise the full-room message.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $remaining = 2; if ($remaining === 0) { echo "Full"; } else { echo "$remaining seats left"; }Test a score that satisfies two overlapping conditions.
At score 85 check >=80 before >=50.
Expected result
high — only the first true branch runs. - Multiway Branching: Switch vs PHP 8 Match Expressions
Read the example and try it
A match expression produces a value for the matching input. A default handles an unfamiliar ticket code.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $kind = "child"; echo match ($kind) { "adult" => 8, "child" => 4, default => 0 };Try an integer and its string representation in the same match.
Include separate match arms for 3 and "3".
Expected result
number text - Looping Constructs: While and Do-While Iterations
Read the example and try it
A do-while runs its body once even when the condition will be false. Track the starting value to predict the output.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $attempt = 0; do { echo ++$attempt; } while ($attempt < 0);Trace both loop forms with a condition that starts false.
Both loop conditions start false. Count body executions.
Expected result
0 1 - Counter Iteration: The For Loop and Nested Grids
Read the example and try it
Generate a seat address one row at a time. The inner loop starts again for each new row.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php for ($row = 1; $row <= 2; $row++) { for ($seat = 1; $seat <= 3; $seat++) { echo "$row-$seat "; } }Trace the index values of a three-iteration loop.
Start index at 0 and continue while less than 3.
Expected result
0 1 2 - Array Traversing & Flow Control: Foreach, Break and Continue
Read the example and try it
Skip cancelled requests with continue. Later requests still get processed.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php foreach (["booked", "cancelled", "booked"] as $id => $state) { if ($state === "cancelled") { continue; } echo $id, " "; }Skip unavailable seats and stop after the first accepted one.
Try A=unavailable, B=available, C=available.
Expected result
B — skip A and stop before visiting C.
4. Arrays & Data Structures
- Indexed Arrays: Creation, Modification & Zero-Based Indexing
Read the example and try it
Appending chooses the next integer key. Read the last seat after placing a third label in the list.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $seats = ["A1", "A2"]; $seats[] = "A3"; echo $seats[2];Remove the middle entry and compare keys before and after reindexing.
Remove index 1 from ["A","B","C"].
Expected result
[0,2] [0,1] - Associative Arrays: Key-Value Pairs, Lookup & Validation
Read the example and try it
A room with unknown capacity is different from a room missing from the directory. Test the presence of the key separately.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $rooms = ["Lab" => null]; var_dump(array_key_exists("Lab", $rooms), isset($rooms["Lab"]));Compare key existence for missing, null and zero values.
Test absent, present-null and present-zero keys with array_key_exists, then isset.
Expected result
[[false,false],[true,false],[true,true]] - Multidimensional Arrays: Nested Trees, Matrices & Traversals
Read the example and try it
Choose a row before a seat within that row. Giving each row a name can make the lookup easier to read.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $rows = ["front" => [4, 7], "back" => [8, 9]]; echo $rows["back"][0];Read a room name from the second booking record.
Set booking room names to Lab then Hall.
Expected result
Hall - Array Functions Pipeline: map, filter, reduce & Sorting
Read the example and try it
Filtering can preserve gaps in numeric keys. Sum the retained fares and inspect the keys that survived.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $fares = array_filter([2, 8, 5], fn($p) => $p >= 5); echo array_sum($fares), " at keys ", implode(",", array_keys($fares));Filter a numeric array and decide whether to reindex it.
Keep positive values from [0,4,0,6] and compare keys before and after array_values.
Expected result
[1,3] [0,1] - Modern Array Features: Destructuring, Spread Operator & Unpacking
Read the example and try it
Unpack the row and seat from a pair. Their order in the input determines which variable receives which number.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php [$row, $seat] = [3, 8]; echo "Row $row, seat $seat";Unpack two coordinates into named variables.
Unpack [3,5] into x and y.
Expected result
3 5
5. Strings & Regular Expressions
- String Literals: Quotes, Variable Interpolation, Heredoc & Nowdoc
Read the example and try it
Double quotes expand a variable inside a label. Single quotes keep the name as literal text.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $zone = "East"; echo "Gate $zone", PHP_EOL, 'Gate $zone';Print a template containing a literal variable name.
Make the template show the literal characters $room.
Expected result
Room: $room - Core String Manipulation: strlen, strpos, substr & Multi-byte mbstring
Read the example and try it
A match at position zero is still a match. Compare explicitly with false when checking a prefix using strpos.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $start = strpos("Lab 4", "Lab"); var_dump($start, $start !== false);Compare byte counts for an ASCII word and one containing accents.
Compare Cafe and Café using UTF-8 bytes.
Expected result
4 5 - String Splitting, Joins & PHP 8 Search Helpers
Read the example and try it
Split a saved route at its delimiter, then join the pieces into a display label. Each piece stays in the same order.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $stops = explode("/", "Park/Lake/Hill"); echo implode(" -> ", $stops);Split a comma list and join it again with a different separator.
Split Lab,Hall,Gym and join with a slash.
Expected result
Lab/Hall/Gym - Regular Expressions: PCRE Engine, Pattern Matching & Replacement
Read the example and try it
Anchor the pattern at both ends to check the entire label. A valid prefix alone is insufficient.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php foreach (["S-42", "S-421"] as $id) { echo preg_match('/^S-[0-9]{2}$/D', $id), PHP_EOL; }Test a valid nonmatch and inspect the error case separately.
Test a digit-only pattern on "Lab", then an invalid pattern. Inspect strictly.
Expected result
0 false — valid nonmatch and regex compilation error respectively. The invalid pattern normally emits a warning. - Text Formatting, Sanitization, Number Format & Cryptographic Hashing
Read the example and try it
Formatting a price creates display text. Keep the original number for later arithmetic.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $fare = 12.5; echo number_format($fare, 2), " for one, ", number_format(2*$fare, 2), " for two";Separate displaying a formatted price from verifying a secret.
Format 3.5 to two decimals. Hash the practice secret demo and verify it.
Expected result
3.50 true. Salted hash text varies.
6. Functions & Modular Programming
- User-Defined Functions: Declaration, Return Types & Scopes
Read the example and try it
A return value can feed another expression. This function calculates the total before the caller adds a booking fee.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php function bill(int $seats, int $fare): int { return $seats * $fare; } echo bill(3, 4) + 1;Declare a function returning an integer count.
Pass [2,4,6] to a function declared to return int.
Expected result
3 - Argument Passing: By-Value vs By-Reference (&) Mechanics
Read the example and try it
An ampersand lets the function edit the caller's variable. Compare the stock before and after the call.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php function reserve(int &$left): void { $left--; } $stock = 6; reserve($stock); echo $stock;Increment a counter once by value and once by reference.
Start at 4. Call an increment by value and then by reference.
Expected result
4 5 - Modern Arguments: Default Values, Named Arguments & Variadics (...)
Read the example and try it
Default arguments cover the common case. Named arguments let a caller specify a different rate explicitly.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php function cost(int $count, int $rate = 3): int { return $count * $rate; } echo cost(2), " ", cost(count: 2, rate: 5);Call a variadic total function with zero and three values.
Sum no arguments, then sum 2,3,5.
Expected result
0 10 - First-Class Callables: Anonymous Closures & Arrow Functions fn()
Read the example and try it
An arrow function captures the surrounding bonus by value. It adds the same bonus to each score.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $bonus = 2; print_r(array_map(fn($score) => $score + $bonus, [4, 7]));Compare an arrow function using a captured fee with a closure using an explicit reference.
Capture rate=4 in an arrow and by reference in a closure. Change rate to 5; price two seats.
Expected result
8 10 - Modular Architecture: include, require, include_once & require_once
Read the example and try it
Build a path relative to the current file. Load a helper only if the small demonstration project contains it.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $helper = __DIR__ . "/seat_helpers.php"; if (is_file($helper)) { require_once $helper; } else { echo "Add seat_helpers.php beside this file"; }Choose loading behavior for essential and optional files.
One file configures the database; the other displays an optional banner.
Expected result
Use require for essential configuration. An unhandled missing required file stops normal execution. Guard the optional include or handle its absence and continue without the banner.
7. Web Concepts & Form Processing
- Client-Server Architecture: HTTP Requests, Response Cycles & Superglobals
Read the example and try it
The request method is available in a web request. A terminal demonstration can supply its own fallback.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $method = $_SERVER["REQUEST_METHOD"] ?? "CLI"; echo "This request arrived through ", $method;Trace a submitted seat count from the browser to the PHP handler.
Send an ordinary URL-encoded POST with seats=3 to a local PHP handler.
Expected result
The request method is POST and $_POST['seats'] contains the string "3". The server checks the integer range before using it. - HTTP Methods: GET vs POST Data Processing & Differences
Read the example and try it
Give the text box a name so its value reaches PHP. Save this as a local PHP page, submit 4, then try a blank field.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php ?><form method="get"><label>Seats <input name="seats"></label><button>Check</button></form> <?php $seats = filter_input(INPUT_GET, "seats", FILTER_VALIDATE_INT); if (is_int($seats) && $seats > 0) { echo "Requested: ", $seats; }Separate a shareable search URL from a booking submission.
Use a search for room=Lab and a write that creates a booking.
Expected result
A shareable lookup can use GET /search.php?room=Lab. Create via POST with validated fields and appropriate CSRF protection. Refreshing the search does not create a booking. - Form Validation & Sanitization: XSS Prevention & filter_var
Read the example and try it
Read the submitted seat count as a whole number. Check the lower and upper limits on the server before multiplying the accepted count by four credits.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $submitted = array_key_exists('seats', $_GET); $count = filter_input(INPUT_GET, 'seats', FILTER_VALIDATE_INT, [ 'options' => ['min_range' => 1, 'max_range' => 6], ]); ?> <form method="get"> <label>Seats (1 to 6) <input name="seats"></label> <button>Check quote</button> </form> <?php if ($submitted) { echo is_int($count) ? 'Quote: ' . ($count * 4) . ' credits' : 'Enter a whole number from 1 to 6.'; }Test the quote form with zero, three and a nonnumeric value.
Use whole counts 1–6 at four credits per seat. Test 0, 3 and bus.
Expected result
0 → Enter a whole number from 1 to 6. 3 → Quote: 12 credits bus → Enter a whole number from 1 to 6. - State Management: Cookies, setcookie & Modern Security Flags
Read the example and try it
A browser stores a cookie from the response and sends it on a later visit. Run this page over local HTTPS to test the secure flag.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php setcookie("display_mode", "large", ["secure"=>true, "httponly"=>true, "samesite"=>"Lax"]); echo $_COOKIE["display_mode"] ?? "Refresh after the cookie is stored";Distinguish HttpOnly from Secure and SameSite.
Inspect a Set-Cookie header with HttpOnly; Secure; SameSite=Lax.
Expected result
HttpOnly restricts script access, Secure restricts normal transmission to HTTPS, and Lax limits cookies on certain cross-site requests. These are three separate controls. - Session Management: session_start, State Persistence & Regeneration
Read the example and try it
Start the session before writing the page. Reloading with the same session cookie increments the same visit count.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php session_start(); $_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1; echo $_SESSION["visits"];Trace anonymous and authenticated session identifiers.
Compare the session ID before login with the ID after successful authentication and regeneration.
Expected result
The IDs differ while the authenticated session retains the intended user. Check equality as a boolean rather than logging the actual IDs.
8. Files, I/O & System Operations
- Stream I/O: fopen, fread, fwrite, fgets & fclose Handlers
Read the example and try it
Use an in-memory stream to practise file operations. Rewind after writing or the next read starts at the end.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $file = fopen("php://memory", "w+"); fwrite($file, "Room 7"); rewind($file); echo fgets($file); fclose($file);Choose file modes for appending a log and replacing a report.
A temporary file starts as A. Append B, then reopen in write mode and write C.
Expected result
AB then C. - Convenience I/O: file_get_contents, file_put_contents & Context Streams
Read the example and try it
Write a short message to a temporary file. Compare the read result strictly with false so an empty file remains valid.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $path = tempnam(sys_get_temp_dir(), "seat"); try { file_put_contents($path, "A4"); $label = file_get_contents($path); if ($label !== false) { echo $label; } } finally { unlink($path); }Compare a cooperating reader with a plain unlocked read.
A writer holds an exclusive lock. A second process tries LOCK_SH|LOCK_NB.
Expected result
The cooperating reader cannot acquire the shared lock until the writer releases it. An unlocked read offers no portable coordination guarantee; behavior can depend on the filesystem. - Secure File Uploads: $_FILES Superglobal, MIME Types & Security
Read the example and try it
Inspect the upload error before reading its temporary file. The client's proposed name and type are untrusted. This example only inspects a file.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $upload = $_FILES["badge"] ?? []; if (($upload["error"] ?? null) === UPLOAD_ERR_OK && is_uploaded_file($upload["tmp_name"])) { echo (new finfo(FILEINFO_MIME_TYPE))->file($upload["tmp_name"]); } else { echo "Select a badge file in a multipart form"; }Design checks for a size-limited image upload.
Allow PNG images up to 100 KiB. Try a valid tiny PNG, a 101 KiB file, and text renamed photo.png.
Expected result
Accept only the valid in-limit image after verifying the upload and content. Reject the oversized file and the renamed text. Store accepted files with server-chosen names. - Error Handling: Error Reporting, Custom Handlers & Logging
Read the example and try it
Separate a user-facing message from a server log entry. Include an operation label in logs so you can find the failed step.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $capacity = -1; if ($capacity < 0) { error_log("room import: negative capacity"); echo "Check the room capacity."; }Give a user a short failure message while retaining diagnostic context.
Simulate a database failure with request ID Q17.
Expected result
The user sees a short failure message and Q17. Protected server logs record the operation, Q17 and diagnostic details without credentials. The response omits the stack trace. - Robust Exceptions: try, catch, finally, Custom Exceptions & Throwable
Read the example and try it
An exception passes control to a matching catch. The finally block runs on either path.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php try { throw new DomainException("Seat already taken"); } catch (DomainException $problem) { echo $problem->getMessage(); } finally { echo " (check finished)"; }Trace cleanup after a normal return and a caught exception.
Track one normal return and one thrown exception caught by the caller.
Expected result
cleanup ok; cleanup caught. In each call finally runs before the caller receives the result or exception.
9. Object-Oriented PHP (OOP)
- Classes, Objects & Constructors: PHP 8 Constructor Property Promotion
Read the example and try it
Construction supplies a value for each new object. Creating another ticket produces a separate seat property.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php class SeatTicket { public function __construct(public int $seat) {} } $one = new SeatTicket(8); echo $one->seat;Create two objects and compare their independent properties.
Create two rooms with 8 seats and change the first to 3.
Expected result
3 8 - Encapsulation: Access Modifiers (public, protected, private) & Getters/Setters
Read the example and try it
Encapsulation protects the rule that remaining seats cannot go below zero. Only the reservation method changes the count.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php class Room { private int $left = 1; public function reserve(): bool { if ($this->left === 0) { return false; } $this->left--; return true; } } $room = new Room(); var_dump($room->reserve(), $room->reserve());Protect a balance and update it through a checked method.
Start a private balance at 5. Allow withdrawal only when the amount is positive and covered. Try 4 then 3.
Expected result
First accepted, second rejected, balance 1. - Inheritance & Polymorphism: Extends, Overriding & parent:: Keyword
Read the example and try it
An overriding method can build on its parent's calculation. Here a return trip costs two single fares.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php class Ticket { public function fare(): int { return 4; } } class ReturnTicket extends Ticket { public function fare(): int { return 2 * parent::fare(); } } echo (new ReturnTicket())->fare();Call the same method on two child implementations.
Have Room and Lab implement the same label method with different results.
Expected result
Room Lab - Contracts & Abstraction: Abstract Classes vs Interfaces
Read the example and try it
An interface tells the caller which method it can use. The concrete class decides how to produce the result.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php interface Label { public function text(): string; } class GateLabel implements Label { public function text(): string { return "Gate B"; } } function show(Label $label): void { echo $label->text(); } show(new GateLabel());Design an interface and two classes satisfying it.
Define Bookable::reserve():bool. Two implementations return true and false.
Expected result
[true,false] - Modular Reuse: Traits, Namespaces & PSR-4 Autoloading
Read the example and try it
A trait supplies a method to a class without creating another parent class. A namespace keeps this class name separate from others.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php namespace Study; trait SeatLabel { public function label(): string { return "Seat 4"; } } class Ticket { use SeatLabel; } echo (new Ticket())->label();Place similarly named classes in two namespaces.
Use the name Room in Campus and Town namespaces.
Expected result
Campus\Room and Town\Room are distinct class names.
10. Database, Web Services & Interview Guide
- MySQL Database Architecture: PDO vs MySQLi Drivers & Connections
Read the example and try it
Inspect the PDO drivers installed in this runtime. Installing a database server and enabling its PHP driver are separate setup steps.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php echo in_array("mysql", PDO::getAvailableDrivers(), true) ? "PDO MySQL ready" : "Enable pdo_mysql";Replace a concatenated lookup value with a placeholder.
Create an in-memory SQLite table via PDO containing O'Brien. Bind the lookup value.
Expected result
O'Brien - CRUD Operations & SQL Injection Defense: Prepared Statements
Read the example and try it
Bind a value after preparing the SQL structure. This in-memory SQLite example requires pdo_sqlite and uses the same placeholder idea as PDO MySQL.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $db = new PDO("sqlite::memory:"); $db->exec("CREATE TABLE seats (label TEXT)"); $save = $db->prepare("INSERT INTO seats (label) VALUES (?)"); $save->execute(["A-7"]); echo $db->query("SELECT label FROM seats")->fetchColumn();Allow two sort columns while binding the search value.
Permit sort columns name and seats only. Try sort=owner with search value O'Brien.
Expected result
Reject owner or choose a documented safe default. For name or seats, build ORDER BY from the allowlist and bind O'Brien as a value separately. - Password Hashing & Modern Security: Argon2id, Bcrypt & Verification
Read the example and try it
Hash a practice password once and verify candidate input against the stored hash. A new hash can differ even for the same input.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php $hash = password_hash("practice-pass-7", PASSWORD_DEFAULT); var_dump(password_verify("practice-pass-7", $hash), password_verify("wrong", $hash));Test a matching password and one incorrect guess.
Hash the practice password yes; compare candidates yes and no.
Expected result
[true,false] - RESTful Web APIs: JSON Responses, HTTP Statuses & CORS Headers
Read the example and try it
Send a status and a content type before writing the body. A client can then interpret the seat count as JSON data.
PHP 8. Save as a .php file. Browser forms, cookies, uploads and sessions require a request through a local web server.
<?php header("Content-Type: application/json"); http_response_code(200); echo json_encode(["room"=>"Lab","available"=>4], JSON_THROW_ON_ERROR);Return different responses for malformed input and successful creation.
For a local create handler, send broken JSON then {"name":"Lab"} with all required fields.
Expected result
Broken JSON → HTTP 400 with a JSON error. Valid input → HTTP 201 and a created resource identifier. A success response should follow successful persistence. - PHP Revision: Function Contracts, Validation & Output Contexts
Trace changing state and check loop boundaries
A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.
Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.
PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
total ← total + value
RETURN totalCheck the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.
Validate input and encode PHP HTML output
Validation and output encoding solve different problems. Validation decides whether a value is acceptable for the application. Encoding preserves text when it is inserted into HTML. htmlspecialchars is appropriate for the HTML text context below; it is not a universal encoder for JavaScript, CSS, or URLs. Prepared database statements are a separate defense for SQL values.
PHP 8; Django and ASP.NET learners should use their template system equivalents
<?php
$name = $_GET["name"] ?? "Student";
if (!is_string($name) || strlen($name) > 80) {
http_response_code(400);
exit("Invalid name");
}
?>
<p>Hello, <?= htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?></p>Check the output
For name=Asha the browser displays: Hello, Asha. Markup supplied as a name is displayed as text in this context.Explain why putting the same value inside a script block needs different handling. Never infer server security merely because PHP source is not normally sent to the browser.
Open the PHP learning path on DevStudyHub · Play coding games on this blog
No comments:
Post a Comment
Please do not enter any spam link in the comment box.