One-page revision site

Internet Programming 622 Study Hub

A dark, readable study page for the supplied guide: PHP forms, request handling, cookies, sessions, file operations, SQL, MySQL connections, and local XAMPP execution.

Definitions Correct patterns Exam traps Security risks Architecture

Exam Focus Areas

Use this first for high-yield revision. Each card points to the exact section where the idea is explained in the chapter content.

Exam Overview

The guide is built around four practical PHP areas: collecting user input, preserving state across stateless HTTP requests, storing or reading server-side files, and using relational databases through SQL and PHP database connections.

Topic What You Must Be Able To Do Typical Question Style
Forms Create forms, choose GET or POST, read values through PHP superglobals, handle missing fields, validate input. Write or fix a PHP form handler.
State Explain why HTTP is stateless, use cookies and sessions, destroy sessions, compare persistence choices. Build login, preference, or multi-step form logic.
Files Check file information, open files, read/write content, move file pointers, manage directories. Write a file script, hit counter, CSV reader, or directory listing.
SQL/MySQL Define RDBMS concepts, create tables, insert/select/update/delete rows, connect PHP to MySQL. Write SQL statements and PHP query code.
Exam Focus Forms

Forms and Request Data

A form collects browser input, sends it to the URL in the action attribute, and uses method="get" or method="post" to decide how the values travel to PHP.

  • GET appends data to the URL and is better for small, bookmarkable requests.
  • POST sends data in the request body and is better for larger or more sensitive submissions.
  • PHP reads submitted values through $_GET, $_POST, or the broader $_REQUEST.
Exam trap: Know which controls send nothing when empty: unchecked checkboxes, unselected radio groups, list boxes with no selection, reset buttons, and ordinary push buttons.
Security Validation

Security and Validation

User input must never be trusted. The guide highlights XSS risk when raw submitted data is printed back into HTML, and it uses htmlspecialchars(), filter_var(), isset(), and empty() as core defensive tools.

  • Escape output before displaying it in HTML.
  • Validate format, for example checking email with FILTER_VALIDATE_EMAIL.
  • Check whether optional controls exist before reading them.
Security trap: Never display passwords back to the user, and do not echo raw $_POST or $_GET values into the page.
State HTTP

Cookies and Sessions

HTTP is stateless, so PHP needs a way to remember information across page views. Cookies store small data in the browser, while sessions store server-side data linked to a session ID, usually held in the PHPSESSID cookie.

  • setcookie() must run before page output because cookies are headers.
  • session_start() loads session variables into $_SESSION.
  • session_destroy() removes session data, useful for logout flows.
Exam trap: Putting a session ID in the URL can expose it in the address bar. Prefer secure cookies and HTTPS where possible.
File I/O Permissions

Files and Directories

PHP can store persistent data in server-side files and folders. The guide expects you to check whether files exist, inspect metadata, open handles, read/write safely, and close file or directory handles.

  • Use file_exists(), filesize(), filemtime(), and basename() for file information.
  • Use fopen(), fread(), fgets(), fwrite(), and fclose() for handle-based work.
  • Use opendir(), readdir(), and closedir() for directories.
Correct pattern: Check before acting, handle failed opens, and close handles after reading or writing.
SQL RDBMS

SQL and MySQL

Databases solve the limitations of large flat files by allowing efficient querying, filtering, relationships, and structured storage. You should know relational tables, rows, columns, primary keys, indexes, and CRUD SQL.

  • CREATE builds databases and tables.
  • INSERT, SELECT, UPDATE, and DELETE manipulate table data.
  • DROP removes a table or database permanently.
Exam trap: UPDATE or DELETE without a WHERE clause affects every row in the table.
Setup Local PHP

XAMPP Setup

XAMPP gives you Apache, MySQL, PHP, and Perl in a local package so you can run and test PHP web pages before publishing them. PHP files are placed under htdocs and accessed through localhost.

  • Start Apache in the XAMPP control panel before opening PHP files in a browser.
  • Use a .php extension so the server sends the file through PHP.
  • Open pages through localhost/folder/file.php, not by double-clicking the PHP file.

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.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

Final Revision Tables

Fast recall tables for the functions and statements most likely to matter in practical questions.

PHP Request and Security Functions

Item Use
$_GETRead query string or GET form values.
$_POSTRead POST form values.
htmlspecialchars()Escape output to reduce XSS risk.
filter_var()Validate formatted data such as email addresses.
isset()Check whether a submitted key exists.
empty()Check whether a value is missing or empty.

PHP State, File, and Directory Functions

Item Use
setcookie()Create browser cookies before output.
session_start()Begin or resume a session.
fopen() / fclose()Open and close file handles.
fgets() / fwrite()Read lines and write strings.
opendir() / readdir()Open and iterate through directories.
is_file() / is_dir()Test whether a path is a file or directory.

SQL Statement Quick Table

Statement Purpose Example
CREATECreate a database or table.CREATE DATABASE mydatabase;
INSERTAdd a row.INSERT INTO fruit (name) VALUES ('plum');
SELECTRetrieve rows.SELECT * FROM fruit;
UPDATEModify rows.UPDATE fruit SET color='yellow' WHERE id=1;
DELETEDelete rows.DELETE FROM fruit WHERE id=1;
DROPRemove a table or database.DROP TABLE fruit;

Practical Coding Checklist

  1. Choose the right request method and matching superglobal.
  2. Use isset() or empty() before reading optional form values.
  3. Validate input and escape output with htmlspecialchars().
  4. Start sessions before using $_SESSION.
  5. Close files, directories, and database connections after use.
  6. Use WHERE with UPDATE and DELETE.
  7. Open PHP through localhost when using XAMPP.