Lessons → PHP Basics → Lesson 9

Forms & User Input

PHP
⏱ 20 min read📖 BeginnerNot completed

PHP excels at handling HTML forms. You can collect user input through $_GET and $_POST superglobals, validate it, and process it.

HTML Form Basics

HTML
<!-- form.html -->
<form action="process.php" method="POST">
    <input type="text" name="username" placeholder="Enter name" />
    <input type="email" name="email" placeholder="Enter email" />
    <button type="submit">Submit</button>
</form>

$_POST — Handling Form Data

PHP — process.php
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = $_POST["username"];
    $email    = $_POST["email"];

    echo "Name: $username";
    echo "Email: $email";
}
?>

$_GET — URL Parameters

PHP
<?php
// URL: page.php?name=John&age=25

$name = $_GET["name"];  // John
$age  = $_GET["age"];   // 25

// Safe way with null coalescing
$name = $_GET["name"] ?? "Guest";
?>

Validation

PHP
<?php
$errors = [];
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");

// Required field
if (empty($name)) {
    $errors[] = "Name is required.";
}

// Minimum length
if (strlen($name) < 2) {
    $errors[] = "Name must be at least 2 characters.";
}

// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email address.";
}

if (empty($errors)) {
    echo "Form submitted successfully!";
} else {
    foreach ($errors as $error) {
        echo "<p style='color:red'>$error</p>";
    }
}
?>

Sanitizing Input (XSS Prevention)

PHP
<?php
// ALWAYS sanitize before displaying user input!
$name = htmlspecialchars($_POST["name"], ENT_QUOTES, 'UTF-8');

// This converts: <script>alert('XSS')</script>
// To safe text:  &lt;script&gt;...
echo $name;  // Safe to display

// For database — use prepared statements (see MySQL lesson)
?>
💡
In Laravel, validation is much easier! Use the validate() method in controllers: $request->validate(['name' => 'required|min:2', 'email' => 'required|email']) — Laravel handles errors automatically.
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz.

Take Quiz →