Creating a Basic HTML Form

To get started, we will create a basic HTML form. This form will collect a user's name and email address. Create a new file named form.php and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple PHP Form</title>
</head>
<body>
    <h1>User Information Form</h1>
    <form action="form.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Handling Form Submission

Next, we need to handle the form submission. When the user submits the form, we will process the input data. Modify the form.php file to include the following PHP code at the top:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Collect and sanitize input data
    $name = htmlspecialchars(trim($_POST['name']));
    $email = htmlspecialchars(trim($_POST['email']));

    // Validate email
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "<h2>Thank you, $name!</h2>";
        echo "<p>Your email address is: $email</p>";
    } else {
        echo "<h2>Invalid email format.</h2>";
    }
}
?>

Explanation of the Code

  1. Form Structure: The form uses the POST method to submit data to the same page (form.php). Each input field has a corresponding label for accessibility.
  1. Form Handling: The PHP block checks if the request method is POST, indicating that the form has been submitted. It retrieves the values of name and email from the $_POST superglobal.
  1. Sanitization: The htmlspecialchars function is used to prevent XSS (Cross-Site Scripting) attacks by converting special characters to HTML entities. The trim function removes any unnecessary whitespace.
  1. Validation: The filter_var function is employed to validate the email format. If the email is valid, a thank-you message is displayed; otherwise, an error message is shown.

Best Practices for Form Handling

When working with forms in PHP, consider the following best practices:

Best PracticeDescription
Use HTTPSAlways use HTTPS to encrypt data submitted through forms.
Sanitize InputSanitize all user input to prevent XSS and SQL injection attacks.
Validate InputValidate data on the server side to ensure it meets expected formats.
Use Prepared StatementsWhen interacting with databases, use prepared statements to prevent SQL injection.
Provide User FeedbackAlways inform users of successful submissions or errors.

Enhancing the Form with CSS

To improve the user experience, you can add some basic CSS styling. Add the following <style> section inside the <head> of your form.php file:

<style>
    body {
        font-family: Arial, sans-serif;
        margin: 20px;
    }
    form {
        border: 1px solid #ccc;
        padding: 20px;
        border-radius: 5px;
        width: 300px;
    }
    input[type="text"],
    input[type="email"] {
        width: 100%;
        padding: 10px;
        margin: 5px 0 15px 0;
        border: 1px solid #ccc;
        border-radius: 4px;
    }
    input[type="submit"] {
        background-color: #4CAF50;
        color: white;
        padding: 10px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    input[type="submit"]:hover {
        background-color: #45a049;
    }
</style>

Conclusion

In this tutorial, you learned how to create a simple web form using PHP, handle form submissions, and validate user input. You also explored best practices for secure form handling and enhanced the form's appearance with CSS. This foundational knowledge will enable you to build more complex forms and applications in PHP.

Learn more with useful resources