New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming PHP PHP Forms and User Input

PHP Forms and User Input

🐘 PHP

Process HTML form data with PHP.

Lesson 3 of 5 Tutorial
0/5 completed

PHP Forms

HTML Form

<form method="POST" action="process.php">
    <input type="text" name="username" required>
    <input type="email" name="email" required>
    <button type="submit">Register</button>
</form>

PHP Processing

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $username = trim($_POST["username"] ?? "");
    $email = trim($_POST["email"] ?? "");

    // Sanitize
    $username = htmlspecialchars($username);

    echo "Welcome, $username!";
    echo "Your email is: $email";
}
?>
⚠️ Security

Always sanitize user input with htmlspecialchars() to prevent XSS attacks. Never trust user data!

Example

<?php
// Simple form processor
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = htmlspecialchars(trim($_POST["name"] ?? ""));
    $email = htmlspecialchars(trim($_POST["email"] ?? ""));
    $subject = htmlspecialchars($_POST["subject"] ?? "");
    $message = htmlspecialchars($_POST["message"] ?? "");

    if ($name && $email && $message) {
        echo "Message received!
";
        echo "From: $name ($email)
";
        echo "Subject: $subject
";
        echo "Message: $message
";
    } else {
        echo "Please fill all required fields.
";
    }
}
?>

Exercises

Exercise 1. Sanitise Form Input Medium
Read \$_POST['name'], trim it, escape HTML special characters with htmlspecialchars and echo the result.
Use exactly: htmlspecialchars(trim(\$_POST['name'] ?? ''))
<?php
// your code here
Expected Output
The posted name is cleaned and printed safely.

Lesson Nav

Lesson sections