PHP Form Handling
In this page:
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
$_GET['search'] = "php tutorials";
echo $_GET['search'];
?>
Login to try C/C++/Java/PHP code in the editor
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
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo "Form was submitted";
} else {
echo "Just a normal page load";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$_POST['age'] = "25";
$age = $_POST['age'];
if (is_numeric($age) && $age > 0) {
echo "Valid age: $age";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$_POST['comment'] = "<script>alert('xss')</script>";
echo htmlspecialchars($_POST['comment']);
?>
Login to try C/C++/Java/PHP code in the editor
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
// After a successful POST, redirecting avoids duplicate submissions on refresh
$submitted = true;
if ($submitted) {
echo "header('Location: /thank-you.php'); // Post/Redirect/Get pattern";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: