Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the health-check domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/yogisv5/sitesbyyogi.com/wp-includes/functions.php on line 6260
MODULE 7: Working with Forms and User Input - SitesByYogi

StreetGeek Academy · PHP Foundations

🧩 Module 7: Working with Forms and User Input

Objective: Learn how to collect, validate, and sanitize user data in PHP using HTML forms,
$_POST, and $_GET, while ensuring security and data integrity.

🔹 1. Introduction to Forms and User Input

Forms allow users to send data to the server — like login info, comments, or search queries.
PHP processes that data using superglobal variables like $_POST and $_GET.

🧩 Example Form

<form method="POST" action="welcome.php">
  Name: <input type="text" name="username"><br>
  <input type="submit" value="Submit">
</form>

And in welcome.php:

<?php
echo "Welcome, " . $_POST['username'];
?>

✅ When the form is submitted, PHP captures the input and displays it.

🔹 2. Understanding Form Methods: GET vs POST

Method Data Location Use Case Example
GET Appends data to the URL Reading/searching page.php?name=Yogi
POST Sends data in the HTTP body Submitting forms, passwords Used for login or registration

🧠 Rule of Thumb:

  • Use GET for things that don’t change server data.
  • Use POST for things that do change or contain sensitive info.

🔹 3. Handling Form Data Securely

Before using user input in your scripts, always:

  • Validate: Check if the input is in the right format (email, number, etc.)
  • Sanitize: Remove unwanted or malicious characters
  • Escape: Convert special characters to HTML-safe symbols

Sanitizing Input

<?php
$name = htmlspecialchars($_POST['name']);
?>

Prevents HTML or JavaScript injection and converts <script> into harmless text.

Validating Input

<?php
$email = $_POST['email'];

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email!";
} else {
    echo "Invalid email format.";
}
?>

Combining Validation + Sanitization

<?php
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Thanks, $email is valid!";
} else {
    echo "Invalid email.";
}
?>

🔹 4. The $_SERVER["REQUEST_METHOD"] Check

To prevent your page from executing code before submission:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form
}
?>

This ensures your code only runs after form submission.

🔹 5. Error Messages and Required Fields

Good forms provide feedback. Here’s a common pattern:

<?php
$nameErr = $emailErr = "";
$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = htmlspecialchars($_POST["name"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
    }
}
?>

🔹 6. Displaying Form Data Back to the User

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
  Name: <input type="text" name="name" value="<?php echo $name; ?>">
  <span style="color:red;"><?php echo $nameErr; ?></span><br>
  
  Email: <input type="text" name="email" value="<?php echo $email; ?>">
  <span style="color:red;"><?php echo $emailErr; ?></span><br>
  
  <input type="submit" value="Submit">
</form>

<?php
if (!empty($name) && !empty($email)) {
    echo "<h3>Welcome, $name ($email)!</h3>";
}
?>

✅ Output includes both the form and user feedback.

🧩 Hands-On Practice

Exercise 1: Simple Form (form-basic.php)

<form method="POST" action="">
  Enter your name: <input type="text" name="name">
  <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = htmlspecialchars($_POST['name']);
    echo "<p>Hello, $name!</p>";
}
?>

✅ Input your name — it displays safely below the form.

Exercise 2: Email Validation (validate-email.php)

<form method="POST" action="">
  Email: <input type="text" name="email">
  <input type="submit" value="Check Email">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<p style='color:green;'>Valid email address</p>";
    } else {
        echo "<p style='color:red;'>Invalid email format</p>";
    }
}
?>

Exercise 3: Required Fields (required.php)

<form method="POST" action="">
  Name: <input type="text" name="name"><br>
  Message: <textarea name="message"></textarea><br>
  <input type="submit" value="Send">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"]) || empty($_POST["message"])) {
        echo "<p style='color:red;'>All fields are required!</p>";
    } else {
        $name = htmlspecialchars($_POST["name"]);
        $message = htmlspecialchars($_POST["message"]);
        echo "<p>Thank you, $name. Your message has been received:</p>";
        echo "<blockquote>$message</blockquote>";
    }
}
?>

Exercise 4: Sanitization & Display (sanitize.php)

<form method="POST" action="">
  Comment: <textarea name="comment"></textarea><br>
  <input type="submit" value="Post Comment">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $comment = htmlspecialchars($_POST["comment"]);
    echo "<h4>Your Safe Comment:</h4><p>$comment</p>";
}
?>

✅ Test with <script> or HTML tags — PHP safely displays text instead of executing code.

🎯 Mini Project – Feedback Form with Validation (feedback.php)

<?php
$nameErr = $emailErr = "";
$name = $email = $feedback = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = htmlspecialchars($_POST["name"]);
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
    }

    if (!empty($_POST["feedback"])) {
        $feedback = htmlspecialchars($_POST["feedback"]);
    }
}
?>

<h2>Feedback Form</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
  Name: <input type="text" name="name" value="<?php echo $name; ?>">
  <span style="color:red;"><?php echo $nameErr; ?></span><br>
  
  Email: <input type="text" name="email" value="<?php echo $email; ?>">
  <span style="color:red;"><?php echo $emailErr; ?></span><br>
  
  Feedback:<br>
  <textarea name="feedback"><?php echo $feedback; ?></textarea><br>
  
  <input type="submit" value="Submit">
</form>

<?php
if (!empty($name) && !empty($email)) {
    echo "<h3>Thank you, $name!</h3>";
    echo "<p>We’ve received your feedback:</p><blockquote>$feedback</blockquote>";
}
?>

✅ Output includes live error messages and sanitized feedback.

🧾 Module 7 Quiz

# Question Options Correct
1 Which PHP variable stores form data sent via POST? a) $_FORM · b) $_POST · c) $_DATA b
2 What function removes HTML tags? a) sanitize_text() · b) htmlspecialchars() · c) strip_tags() c
3 What will filter_var($email, FILTER_VALIDATE_EMAIL) return if invalid? a) false · b) true · c) null a
4 Which method hides data from the URL? a) GET · b) POST · c) BOTH b
5 What is $_SERVER["REQUEST_METHOD"] used for? a) To display all form data · b) To detect submission type · c) To sanitize input b

💪 Challenge Task – Contact Form with Error Handling and Success Message

Objective: Combine everything from this module to build a complete, safe form handling system
in contact-form.php.

  • Name and Email fields (required)
  • Message field (optional)
  • Inline error messages
  • Success message when submitted correctly

✅ Example output:

  • Name is required.
  • Email is required.
  • ✅ Thank you, Yogi! Your message has been received.

Make sure:

  • You use htmlspecialchars() and filter_input()
  • The form re-populates values after submission

🧾 Submission Checklist

  • form-basic.php → collects user input
  • validate-email.php → email validation works
  • required.php → error handling for empty fields
  • feedback.php → full validation and sanitization
  • ✅ Quiz completed

🏁 Next Step: In Module 8, you’ll go deeper into file handling — learning how to save, read,
and display data from files using PHP. This forms the backbone of basic databases, logging systems, and even
CMS-like storage (before MySQL).