PHP Forms

Learn how to create and handle forms in PHP, including GET and POST methods, validation, and processing form data.

What is a Form in PHP?

A form is an HTML document that collects user input. PHP is often used to process this input once the user submits the form. Forms can include various input types, such as text fields, radio buttons, checkboxes, and submit buttons.

Creating a Simple HTML Form

Here's a basic example of an HTML form:

<form action="process.php" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <input type="submit" value="Submit">
</form>

Form Submission Methods

There are two primary methods for submitting forms in PHP:

  • GET: Appends form data to the URL. Suitable for non-sensitive data. Example: action="process.php?name=John"
  • POST: Sends form data in the HTTP request body. More secure for sensitive information. Use method="post".

Processing Form Data in PHP

To process form data, create a PHP file (e.g., process.php) that retrieves the submitted values:

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

    echo "Name: " . htmlspecialchars($name) . "<br>";
    echo "Email: " . htmlspecialchars($email) . "<br>";
}
?>

Validating Form Data

Always validate and sanitize user input to avoid security risks:

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

    if (empty($name) || empty($email)) {
        echo "Name and email are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
    } else {
        echo "Name: " . $name . "<br>";
        echo "Email: " . $email . "<br>";
    }
}
?>

Conclusion

PHP forms are a powerful way to collect and process user input. Understanding how to create, submit, and validate forms is essential for building dynamic web applications. Always prioritize security by validating and sanitizing user input to protect your application from vulnerabilities.