🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 4
TEC-WEB46-03 · Lesson 4 · 13 clock hours · lab

PHP Forms, Superglobals, and Input Validation

Objective. Students build PHP-powered HTML forms that collect user input via $_GET and $_POST, validate and sanitize input using filter functions, and display safe, meaningful error messages without exposing server details

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

PHP Forms, Superglobals, and Input Validation

Web forms are the front door of nearly every web application. A contact page, a login screen, a shopping cart — all depend on HTML forms that collect user data and send it to a server-side script for processing. PHP handles that server-side work through built-in superglobal arrays and a powerful set of filter functions. Handling form data correctly is not just a programming skill; it is a security responsibility. Unvalidated input is the root cause of some of the most damaging web vulnerabilities in existence.

How HTML Forms Send Data to PHP

An HTML `<form>` element has two key attributes: `action` and `method`. The `action` attribute names the PHP script that will process the submission. The `method` attribute is either `GET` or `POST`.

When PHP receives the request, it automatically populates two superglobal arrays:

A third superglobal, `$_REQUEST`, merges both, but best practice is to use `$_GET` or `$_POST` directly so you know exactly which method you expect.

The PHP Superglobals

Superglobals are built-in PHP arrays accessible from any scope — inside functions, classes, or the global script — without needing the `global` keyword. The ones relevant to forms are:

| Superglobal | Contains |

|---|---|

| `$_GET` | URL query string parameters |

| `$_POST` | HTTP POST body parameters |

| `$_FILES` | Uploaded file metadata |

| `$_SERVER` | Server and request headers (e.g., `REQUEST_METHOD`) |

| `$_SESSION` | Session data across requests |

| `$_COOKIE` | Browser cookies |

Never trust data from any superglobal. Every value that arrives from the browser must be treated as potentially hostile until your code proves otherwise.

Validating and Sanitizing Input

Validation checks that input meets expected rules (e.g., an email address contains `@`). Sanitization cleans the value by removing or encoding dangerous characters. Both steps are necessary, and they are different operations.

PHP provides the `filter_input()` and `filter_var()` functions for both purposes.

```php

// Validate an email from POST

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

if ($email === false || $email === null) {

$errors[] = 'Please enter a valid email address.';

}

// Sanitize a plain text field

$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);

// Validate an integer within a range

$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT,

['options' => ['min_range' => 1, 'max_range' => 120]]);

if ($age === false || $age === null) {

$errors[] = 'Age must be a number between 1 and 120.';

}

```

Common filter constants include `FILTER_VALIDATE_EMAIL`, `FILTER_VALIDATE_INT`, `FILTER_VALIDATE_URL`, `FILTER_SANITIZE_SPECIAL_CHARS`, and `FILTER_SANITIZE_NUMBER_INT`.

Preventing Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) occurs when an attacker submits HTML or JavaScript as form input and your page renders it as markup instead of plain text. A classic payload looks like `<script>alert('hacked')</script>`. If your PHP echoes that value directly, the browser executes it.

The defense is `htmlspecialchars()`, which converts characters such as `<`, `>`, `"`, and `&` into their HTML entity equivalents before output:

```php

echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');

```

Always pass `ENT_QUOTES` and specify the character encoding (`UTF-8`). Apply `htmlspecialchars()` at the point of output — every time you echo user-supplied data into an HTML page.

Safe Error Messages

Error messages should help the user fix the problem without revealing server internals. Do not display PHP error output, file paths, database queries, or stack traces to end users. Configure your production server to log errors rather than display them (`display_errors = Off` in `php.ini`).

Good error message: "Please enter a valid email address."

Bad error message: "mysqli_connect(): Access denied for user 'root'@'localhost'"

Collect errors into an array, then display them after all validation is complete. This gives users a full list of problems rather than one error at a time.

OWASP and the Input Validation Cheat Sheet

The Open Worldwide Application Security Project (OWASP) publishes free, peer-reviewed guidance for web security. The OWASP Input Validation Cheat Sheet (available at owasp.org) lists rules such as:

1. Validate all input on the server side, even if client-side validation exists.

2. Define allowlists (expected characters/formats) rather than denylists.

3. Check length constraints — minimum and maximum.

4. Validate data type (integer, email, URL, etc.).

5. Reject or encode special characters before using input in HTML output, SQL, or shell commands.

Client-side JavaScript validation improves user experience but provides zero security guarantee because any user can disable JavaScript or craft a raw HTTP request that bypasses the browser entirely.

Safety Note

In a professional environment, all code that handles user data must follow your organization's secure-coding policy. Never store plain-text passwords — use PHP's `password_hash()` and `password_verify()`. Treat every piece of untrusted input as a potential attack vector. These habits protect your users, your employer, and your professional reputation.

Key terms10

SuperglobalA built-in PHP array (such as $_GET or $_POST) that is automatically populated by PHP and accessible from any scope in a script without needing the global keyword.
$_GETA PHP superglobal array that holds values submitted to the server as URL query string parameters, typically from HTML forms using method='GET'.
$_POSTA PHP superglobal array that holds values submitted in the HTTP request body, typically from HTML forms using method='POST', keeping data out of the URL.
ValidationThe process of checking that user-supplied input meets expected rules for format, type, length, and range before the application uses it.
SanitizationThe process of cleaning or encoding user-supplied input to remove or neutralize characters that could cause harm if used in HTML output, SQL queries, or other contexts.
Cross-Site Scripting (XSS)A web security vulnerability where an attacker injects malicious HTML or JavaScript into a page through user input; prevented by encoding output with htmlspecialchars().
filter_input()A built-in PHP function that retrieves a value from a superglobal (such as INPUT_POST) and optionally validates or sanitizes it using a specified filter constant.
htmlspecialchars()A built-in PHP function that converts special HTML characters (such as <, >, &, and quotes) into their HTML entity equivalents, preventing browser interpretation of injected markup.
Allowlist (whitelist)A validation strategy that defines exactly which characters, formats, or values are acceptable and rejects everything else — more secure than a denylist approach.
OWASPThe Open Worldwide Application Security Project, a nonprofit that publishes free, widely trusted security guidance including cheat sheets for input validation, authentication, and more.
In class: Students build a multi-field registration form (name, email, age, password) with server-side PHP validation; they test with valid and invalid inputs and confirm all error messages appear correctly without a page crash · Security demonstration: instructor submits a script tag as a form value to an unsanitized version of the form and displays the XSS result; students then add htmlspecialchars() and filter_input() to their own form and verify the attack no longer works · Students read the OWASP Input Validation Cheat Sheet (owasp.org) and list five validation rules applicable to their registration form; they implement all five and document each rule and its corresponding PHP code in their lab log
Materials: PHP manual (filter functions), OWASP Input Validation Cheat Sheet (owasp.org), VS Code, local Apache + PHP environment, student lab log template
Check: Registration form correctly validates all fields, rejects known-bad inputs (empty fields, invalid email format, non-numeric age, script-tag injection), and displays user-friendly errors — pass requires all five validation rules implemented and confirmed by instructor review

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — IT Concepts and Terminology / Web fundamentals
1. A student wants a registration form to send the user's password securely so it does not appear in the browser address bar. Which form method should they use?
CompTIA ITF+ — Security Concepts
2. Which PHP function should be used every time user-supplied data is echoed into an HTML page to prevent Cross-Site Scripting (XSS)?
CompTIA ITF+ — IT Concepts and Terminology / Programming basics
3. A form field labeled 'Age' should accept only integers between 1 and 120. Which filter constant and options array is the correct PHP approach?
CompTIA ITF+ — Security Concepts
4. An attacker submits the value <script>alert('xss')</script> in a name field. The PHP page echoes $_POST['name'] directly. What is the expected result?
CompTIA ITF+ — Security Concepts
5. According to the OWASP Input Validation Cheat Sheet, why is server-side validation required even when client-side JavaScript validation is already in place?
CompTIA ITF+ — Security Concepts
6. What is the key difference between input validation and input sanitization?
CompTIA ITF+ — Security Concepts
7. A developer displays the full PHP error message 'mysqli_connect(): Access denied for user root@localhost' to end users when a database login fails. What is the primary security concern?
CompTIA ITF+ — Security Concepts
8. Which of the following best describes an allowlist (whitelist) approach to input validation, as recommended by OWASP?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.