← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 1 of 8

PHP Form Handling

Handling GET Forms

An HTML form's data arrives in PHP through the $_GET or $_POST superglobal array, depending on the form's method attribute, with each array key matching the corresponding input field's name attribute.

Example: Handling GET Forms

php
<?php
$_GET['search'] = "php tutorials";
echo $_GET['search'];
?>

Handling POST Forms

Checking $_SERVER[REQUEST_METHOD] === POST at the top of a script is the standard way to detect whether the form was actually submitted, versus the page just being loaded normally for the first time.

Example: Handling POST Forms

php
<?php
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Form was submitted";
} else {
    echo "Just a normal page load";
}
?>

Validating Form Submission

Every value coming from $_POST or $_GET should be treated as untrusted user input — always validate its type and content before using it in a database query, a file path, or displayed HTML.

Example: Validating Form Submission

php
<?php
$_POST['age'] = "25";
$age = $_POST['age'];
if (is_numeric($age) && $age > 0) {
    echo "Valid age: $age";
}
?>

Processing Multi-value Inputs

htmlspecialchars() should wrap any user-submitted value before it's echoed back into HTML, preventing a malicious script tag typed into a form field from executing in another visitor's browser (cross-site scripting).

Example: Processing Multi-value Inputs

php
<?php
$_POST['comment'] = "<script>alert('xss')</script>";
echo htmlspecialchars($_POST['comment']);
?>

Checking Empty Inputs

Redirecting after a successful form submission (the Post/Redirect/Get pattern) prevents the browser from resubmitting the same form data if the user refreshes the resulting page.

Example: Checking Empty Inputs

php
<?php
// After a successful POST, redirecting avoids duplicate submissions on refresh
$submitted = true;
if ($submitted) {
    echo "header('Location: /thank-you.php'); // Post/Redirect/Get pattern";
}
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.