PHP User Input (HTML Forms)
In this page:
HTML Forms and PHP
When an HTML <form> is submitted, the browser packages every named input's value and sends it to whatever URL the form's action attribute points to, using the method the form specifies (GET or POST). PHP running at that URL then reads the submitted values out of the corresponding superglobal array.
Example: HTML Forms and PHP
<!DOCTYPE html>
<html>
<body>
<form action="process.php" method="POST">
<input type="text" name="username">
</form>
<?php
// PHP reads the submitted value from $_POST['username']
?>
</body>
</html>
Login to try C/C++/Java/PHP code in the editor
Handling Simple Form Text
$_POST and $_GET are associative arrays where each key matches an HTML input's name attribute. In a live form, PHP populates these automatically per request; while learning, it's normal to simulate a submission by manually assigning values into $_POST so you can test the handling logic without a browser.
Example: Handling Simple Form Text
<?php
// Simulating a form submission for testing
$_POST['username'] = "Alice";
echo $_POST['username'];
?>
Login to try C/C++/Java/PHP code in the editor
Checking if Form is Submitted
Reading $_POST[email] when no form was actually submitted triggers an 'undefined array key' warning. Checking isset($_POST[email]) first, or inspecting $_SERVER[REQUEST_METHOD], lets your script safely distinguish a genuine submission from a first-time page visit.
Example: Checking if Form is Submitted
<?php
if (isset($_POST['email'])) {
echo "Form submitted with: " . $_POST['email'];
} else {
echo "No form submitted yet.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Form Input Sanitization
Any value from $_GET, $_POST, or $_COOKIE originates outside your control and must be treated as untrusted. Passing raw input into HTML output without htmlspecialchars() lets an attacker inject a <script> tag that runs in another user's browser — a classic Cross-Site Scripting (XSS) vulnerability.
Example: Form Input Sanitization
<?php
$_POST['comment'] = "<script>alert('xss')</script>";
echo htmlspecialchars($_POST['comment']);
?>
Login to try C/C++/Java/PHP code in the editor
Default Values for Missing Inputs
Accessing a form key that was never submitted (an unchecked checkbox, say) throws a warning rather than quietly returning nothing. $_POST[newsletter] ?? false sidesteps that by falling back to a sensible default the moment the key is missing, no isset() check required.
Example: Default Values for Missing Inputs
<?php
$newsletter = $_POST['newsletter'] ?? false;
var_dump($newsletter);
?>
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: