General Module Content
Chapter-by-chapter notes from the study guide, with all content visible for continuous revision.
Topic 1: PHP and HTML Forms
Forms are the bridge between browser input and PHP processing. The guide moves from basic form structure to request methods, superglobals, security, empty field handling, dynamic forms, and validation.
1.1 How HTML Forms Work
A web form is a collection of controls inside a <form> element. Typical controls include text fields, passwords, checkboxes, radio buttons, file selectors, hidden fields, select lists, multi-select boxes, text areas, submit buttons, and reset buttons.
Browser form
Submit button
HTTP request
PHP handler
<form action="form_handler.php" method="post">
<label for="email">Email</label>
<input type="email" name="email" id="email">
<button type="submit">Send</button>
</form>
1.2 GET vs POST
The form action says where the data goes. The form method says how it is sent. The guide presents GET as suitable for small amounts of data because values appear in the URL. POST sends data in the request body and is better when more data or more sensitive data is involved.
| Method |
Where Data Appears |
Best Fit |
Watch Out |
GET |
URL query string |
Small requests, links, searches, bookmarkable pages |
Visible in the address bar and limited by URL length |
POST |
Request body |
Larger submissions and sensitive form content |
Refreshing may ask the user to resubmit form data |
1.3 Capturing Form Data With PHP
PHP uses superglobal arrays to expose request data in any scope. The field name becomes the array key, and the submitted value becomes the array value.
$_GET stores form values sent with method="get".
$_POST stores form values sent with method="post".
$_REQUEST combines GET, POST, and COOKIE values, so it can be ambiguous.
$email = $_POST["emailAddress"];
echo htmlspecialchars($email);
Correct pattern: If you know the form uses POST, read from $_POST instead of $_REQUEST.
1.4 PHP Form Data and Security
The guide warns that submitted values can include malicious HTML or JavaScript. Printing raw input can cause cross-site scripting. Escape output with htmlspecialchars() and validate values before using them.
$safeName = htmlspecialchars($_POST["firstName"]);
if (filter_var($_POST["emailAddress"], FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
Never do this: Do not display a submitted password back to the page, and do not use raw request values in HTML output.
1.5 Handling Empty Form Fields
Some controls send an empty value when left blank, while others send no key at all. If the key does not exist, reading it directly can produce an undefined index notice.
| Control |
If Empty or Unselected |
PHP Check |
| Text, password, hidden, textarea, file input |
Field name is sent with an empty value |
empty($_POST["field"]) |
| Checkbox, radio, list box, multi-select |
Nothing may be sent |
isset($_POST["field"]) |
| Reset and push buttons |
Nothing is sent |
Do not rely on them as submitted values |
if (isset($_POST["gender"])) {
echo htmlspecialchars($_POST["gender"]);
}
1.6 Dynamic Forms and Validation
The guide describes a PHP-generated form that checks missing required fields, highlights errors, keeps previous values, and shows a thank-you message only after successful validation.
processForm() checks submitted required fields.
displayForm($missingFields) redisplays the form with feedback.
setValue(), setChecked(), and setSelected() preserve user input.
validateField() marks missing fields for styling.
$missing = [];
foreach (["name", "email", "age"] as $field) {
if (empty($_POST[$field])) {
$missing[] = $field;
}
}
Revision task: Practise validating name, email, and age, then extend the same idea to login forms, multi-select lists, and file uploads.
Back to Exam Focus Areas
Topic 2: Session Controls and Cookies
This topic explains how PHP remembers information between requests. The key idea is state: HTTP forgets, while query strings, cookies, and sessions help applications remember.
2.1 Stateless HTTP
Each browser request is independent. PHP starts with a clean slate, runs the script, then removes variables from memory. Applications such as shopping carts, login systems, forums, and multi-page forms need continuity between requests.
Query string
Cookie
Session ID
Server state
Core idea: State means the application can connect a later request to earlier activity from the same user.
2.2 Cookies
A cookie is a small piece of data sent by the server and stored by the browser. On later requests, the browser sends it back, letting PHP identify preferences or repeat visits.
setcookie("bg", "#000000", time() + 60 * 60 * 2);
if (isset($_COOKIE["bg"])) {
echo htmlspecialchars($_COOKIE["bg"]);
}
name identifies the cookie.
value stores the data.
expire controls lifetime.
path, domain, and secure control where and how it is sent.
Headers first: Call setcookie() before any HTML output.
2.3 Sessions
Sessions store persistent variables on the server and link them to a user through a session ID. PHP commonly stores that ID in a browser cookie called PHPSESSID.
session_start();
$_SESSION["hits"] = ($_SESSION["hits"] ?? 0) + 1;
echo "This page has been viewed " . $_SESSION["hits"] . " times.";
session_start() loads or creates the session.
$_SESSION holds session values.
session_id() gets the current session ID.
session_destroy() destroys session data.
2.4 Cookies vs Sessions
| Feature |
Cookies |
Sessions |
| Storage location |
Browser/client |
Server, linked by session ID |
| Size |
Small; guide notes about 4 KB as a practical limit |
Better for larger temporary state |
| Persistence |
Can last beyond browser close if expiration is set |
Usually expires when the browser closes unless configured |
| Best use |
Preferences and identifiers |
Login state, carts, multi-step forms |
Do not expose session IDs: URL-based session IDs are convenient but can be copied, logged, or intercepted.
2.5 Combining Cookies and Sessions
The guide explains that temporary state can live in a PHP session, while longer-term identity or preference state can be stored in a cookie and then used to retrieve persistent data.
if (isset($_POST["bgcolor"])) {
setcookie("bgcolor", $_POST["bgcolor"], time() + 60 * 60 * 24 * 7);
}
$background = $_COOKIE["bgcolor"] ?? $_POST["bgcolor"] ?? "gray";
Applied pattern: A login system can store the current username in $_SESSION, while a preference cookie remembers a color choice for the next visit.
2.6 Review Tasks
- Create a hardcoded login using sessions, a welcome page, and logout.
- Set, read, display, and delete a
user_preference cookie.
- Create a three-step registration form that preserves values with sessions and destroys the session after final submission.
Back to Exam Focus Areas
Topic 3: File System Management
PHP can work with files and directories on the server. This topic covers file metadata, paths, open modes, reading, writing, pointer movement, copying, deleting, directory traversal, and file-type checks.
3.1 Files, Directories, and Metadata
A file is an ordered sequence of bytes. A directory is a special file that stores file and subdirectory names plus pointers to their locations. PHP provides functions to inspect both.
file_exists()
Checks whether a path exists.
filesize()
Returns size in bytes.
fileatime()
Last access timestamp.
filectime()
Last change timestamp.
filemtime()
Last modification timestamp.
basename()
Extracts the filename from a path.
if (file_exists("example.txt")) {
echo filesize("example.txt");
echo date("Y-m-d", filemtime("example.txt"));
}
3.2 Opening Files With fopen()
fopen() returns a file handle used by later read, write, and close functions. The mode matters because some modes erase existing content.
| Mode |
Meaning |
Main Risk |
r |
Read only; file must exist |
Fails if missing |
w |
Write only; creates file or erases existing file |
Destroys old content |
a |
Append only; writes at the end |
Cannot read without another mode |
r+, w+, a+ |
Read/write variants |
w+ also erases old content |
Portability note: The guide recommends binary mode such as rb when you want to avoid operating-system line-ending conversions.
3.3 Reading and Writing
Use the function that matches the job: whole-file reads for small files, line-by-line reads for logs or CSV data, and pointer-based reads when you need exact positions.
fread()
Reads a specified number of bytes or characters.
fgetc()
Reads one character at a time.
fgets()
Reads one line at a time.
fgetcsv()
Reads CSV rows into arrays.
file()
Reads a file into an array of lines.
file_get_contents()
Reads the whole file into a string.
fwrite()
Writes through an open handle.
file_put_contents()
Writes a full string without manually opening a handle.
$handle = fopen("data.txt", "a");
if ($handle) {
fwrite($handle, "New line" . PHP_EOL);
fclose($handle);
}
3.4 EOF and Random Access
PHP maintains an internal pointer for open files. Some functions move it forward as they read. You can also move it manually.
feof() checks whether the end of the file has been reached.
fseek() moves the pointer to a specific offset.
ftell() returns the current pointer position.
rewind() moves the pointer back to the start.
$handle = fopen("hello_world.txt", "r");
fseek($handle, 7);
echo fread($handle, 5); // world
fclose($handle);
3.5 Working With Directories
Directory handles work like file handles. Open the directory, read each entry, skip . and .., then close the handle.
$handle = opendir("files_dir");
if ($handle) {
while (($file = readdir($handle)) !== false) {
if ($file !== "." && $file !== "..") {
echo htmlspecialchars($file) . "<br>";
}
}
closedir($handle);
}
opendir()
Opens a directory handle.
readdir()
Reads the next entry.
closedir()
Closes the directory handle.
rewinddir()
Moves the pointer back to the first entry.
chdir()
Changes the current working directory.
getcwd()
Returns the current working directory.
mkdir()
Creates a directory.
rmdir()
Removes an empty directory.
3.6 Copy, Rename, Delete, and Test Types
File management functions can change data permanently, so check paths before using them.
copy($source, $destination) copies a file.
rename($old, $new) renames or moves a file.
unlink($path) deletes a file.
is_dir($path) checks for directories.
is_file($path) checks for regular files.
if (file_exists("report.txt")) {
copy("report.txt", "report_backup.txt");
}
Destructive action: unlink() deletes the file. Make sure the target path is correct before calling it.
Back to Exam Focus Areas
Topic 4: Databases and Structured Query Language
This topic moves from file storage limitations to relational databases, SQL statements, and PHP-to-MySQL connection code.
4.1 Database Architecture and RDBMS Concepts
An embedded database runs inside the application and is usually local to one machine. A client-server database can serve multiple applications over a network and centralize administration and backups.
| Concept |
Meaning |
| Table |
Structured storage made of rows and columns. |
| Row / record |
One complete set of related values. |
| Column / field |
One data attribute with the same meaning for every row. |
| Primary key |
A unique identifier for each record. |
| Index |
A sorted structure that speeds lookup but slows some writes. |
4.2 Creating Databases and Tables
Use MySQL commands to create a database, select it, and define tables. End each SQL statement with a semicolon.
CREATE DATABASE mydatabase;
USE mydatabase;
CREATE TABLE fruit (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
color VARCHAR(30) NOT NULL,
PRIMARY KEY (id)
);
Key detail: AUTO_INCREMENT lets MySQL generate the primary key value automatically.
4.3 CRUD SQL
CRUD means create, read, update, and delete. In this guide, the fruit table is used to demonstrate the core SQL statements.
INSERT INTO fruit (name, color) VALUES ('banana', 'yellow');
SELECT * FROM fruit;
SELECT name, color FROM fruit WHERE id >= 2;
UPDATE fruit
SET name = 'grapefruit', color = 'yellow'
WHERE id = 2;
DELETE FROM fruit WHERE id = 2;
High-risk statements: DELETE FROM fruit; removes all rows. DROP TABLE fruit; removes the table itself.
4.4 Connecting PHP to MySQL
The guide explains mysqli and PDO, then shows procedural mysqli connection and query examples. Always check the connection and query result before processing rows.
$conn = mysqli_connect("localhost", "root", "", "mydatabase");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT * FROM fruit");
if (!$result) {
die("Query failed: " . mysqli_error($conn));
}
while ($row = mysqli_fetch_assoc($result)) {
echo "<li>A " . htmlspecialchars($row["name"]) .
" is " . htmlspecialchars($row["color"]) . "</li>";
}
mysqli_close($conn);
4.5 Review Query Patterns
The review work asks you to use an e-commerce schema with Customers and Orders. Practise joins, aggregation, table alteration, and deletion order.
SELECT c.Name, o.OrderID, o.TotalAmount
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID;
SELECT c.Name, SUM(o.TotalAmount) AS TotalSpent
FROM Customers c
INNER JOIN Orders o ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerID, c.Name;
Foreign-key thinking: Delete dependent orders before deleting the customer they reference.
4.6 SQL Vocabulary
SELECT
Retrieves rows and returns a result set.
INSERT
Adds rows to a table.
UPDATE
Modifies existing rows.
DELETE
Deletes rows but leaves the table.
CREATE
Creates databases, tables, or indexes.
ALTER
Changes table structure.
DROP
Deletes a database or table structure.
WHERE
Filters affected or returned rows.
Back to Exam Focus Areas
Addendum: Installing and Running PHP With XAMPP
The addendum explains XAMPP as the local development package used to run PHP and MySQL on your computer before publishing a site.
5.1 What XAMPP Provides
XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It gives you a local web server and database setup for development and testing.
- Apache serves web pages locally.
- MySQL stores relational database data.
- PHP executes server-side scripts.
htdocs is the folder where local projects are usually placed.
5.2 Run PHP
Create a folder inside htdocs, open that folder in your editor, save files with a .php extension, start Apache in XAMPP, then access the page through the browser.
<?php
echo "<h1>My Name is Derek</h1>";
?>
Syntax check: Make sure HTML tags are closed correctly inside echoed strings.
5.3 Localhost Path
If your folder is named Demo and your file is test.php, open it as:
http://localhost/Demo/test.php
Correct pattern: PHP must be served by Apache or another PHP-capable server. Opening a PHP file directly from Finder or File Explorer will not execute the PHP code.
Back to Exam Focus Areas