Lesson 8: Handling Forms in PHP

Forms are a vital part of web applications, enabling user interaction and data submission. This lesson covers handling form submissions using PHP, differentiating between GET and POST methods, and securing user input through validation and sanitization.


8.1 GET vs POST

What are GET and POST Methods?

Both GET and POST are HTTP request methods used to send data from a client (browser) to a server.

GET Method

  • Data is sent in the URL.
  • Advantages:
    • Can be bookmarked or shared.
    • Useful for non-sensitive data like search queries.
  • Disadvantages:
    • Limited amount of data (URL length restrictions).
    • Data is visible in the URL, not suitable for sensitive data.
  • Example:
  • <form method=”GET” action=”process.php”>


    >/form>

    URL after submission: process.php?username=value


POST Method

  • Data is sent in the HTTP request body.
  • Advantages:
    • Secure for sensitive data (passwords, personal information).
    • No limit on data size.
  • Disadvantages:
    • Cannot be bookmarked or shared.
  • Example:
  • <?php



    ?>


Handling GET and POST Data in PHP

  • Using $_GET:
  • <?php
    if (isset($_GET[‘username’])) {
    echo “Username: ” . htmlspecialchars($_GET[‘username’]);
    }
    ?>
  • Using $_POST:
  • <?php
    if (isset($_POST[‘username’])) {
    echo “Username: ” . htmlspecialchars($_POST[‘username’]);
    }
    ?>

8.2 Form Validation

Why Validate Forms?

  • Ensures data integrity and security.
  • Prevents malicious input, such as SQL injection or XSS attacks.
  • Enhances user experience with immediate feedback.

Common Validation Rules

  1. Required Fields: Ensure that critical fields are not left empty.
  2. Data Type Validation: Check if the input matches the expected format (e.g., email, number).
  3. Length Validation: Limit the number of characters.
  4. Custom Rules: Define application-specific rules (e.g., password complexity).

Example: Validating Required Fields

<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = trim($_POST[‘name’]);
$email = trim($_POST[’email’]);

if (empty($name)) {
echo “Name is required.
“;
}

if (empty($email)) {
echo “Email is required.
“;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo “Invalid email format.
“;
}
}
?>

Name:
Email:


8.3 Sanitizing and Validating Input

Sanitization vs Validation

  • Sanitization: Cleans input by removing unwanted characters (e.g., HTML tags, special characters).
  • Validation: Ensures input meets specific criteria (e.g., correct email format).

Sanitizing Input

PHP provides the filter_var() function for sanitization.

<?php
$dirty_email = “user@example.com”;
$clean_email = filter_var($dirty_email, FILTER_SANITIZE_EMAIL);
echo $clean_email; // Outputs: user@example.com
?>

Validating Input

PHP provides several filters for validation.

<?php
$email = “user@example.com”;

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo “Valid email.”;
} else {
echo “Invalid email.”;
}
?>


Combining Sanitization and Validation

<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$email = filter_var(trim($_POST[’email’]), FILTER_SANITIZE_EMAIL);

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo “Valid email: $email”;
} else {
echo “Invalid email format.”;
}
}
?>

Email:


Validating Multiple Inputs

<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = htmlspecialchars(trim($_POST[‘name’]));
$email = filter_var(trim($_POST[’email’]), FILTER_SANITIZE_EMAIL);
$age = filter_var(trim($_POST[‘age’]), FILTER_SANITIZE_NUMBER_INT);

if (empty($name)) {
echo “Name is required.
“;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo “Invalid email format.
“;
}

if ($age < 1 || $age > 120) {
echo “Invalid age.
“;
}
}
?>

Name:
Email:
Age:


Activities and Exercises

  1. GET vs POST:
    • Create a form with GET and POST methods to submit a username. Display the username after submission.
  2. Form Validation:
    • Build a form with fields for name, email, and age. Validate all fields to ensure they are filled correctly.
  3. Sanitization and Validation:
    • Write a script that accepts a URL input, sanitizes it, and validates if it is a valid URL.

Assignment

  1. Create a PHP script with a form to collect:
    • Full Name
    • Email Address
    • Age
    • Phone Number
  2. Implement:
    • Validation rules:
      • Name and email are required.
      • Email must be in a valid format.
      • Age must be a number between 1 and 120.
      • Phone number must contain only digits and be 10–15 characters long.
    • Sanitization for all inputs.
  3. Display:
    • Error messages for invalid inputs.
    • A success message and the sanitized data if all inputs are valid.

Summary

In this lesson, you learned how to:

  1. Differentiate between GET and POST methods.
  2. Handle and validate form data in PHP.
  3. Sanitize user inputs to secure your application.

These skills are critical for building secure and user-friendly web applications. Let me know if you’d like further clarification or examples!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *