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
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.
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.
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.
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.
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`.
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.
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.
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.
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.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.