← Back to PHP Course | Chapter 2: Output & Input | Lesson 3 of 8

PHP User Input (HTML Forms)

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

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>

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
<?php
// Simulating a form submission for testing
$_POST['username'] = "Alice";
echo $_POST['username'];
?>

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
<?php
if (isset($_POST['email'])) {
    echo "Form submitted with: " . $_POST['email'];
} else {
    echo "No form submitted yet.";
}
?>

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
<?php
$_POST['comment'] = "<script>alert('xss')</script>";
echo htmlspecialchars($_POST['comment']);
?>

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
<?php
$newsletter = $_POST['newsletter'] ?? false;
var_dump($newsletter);
?>
🔒

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.