Skip to main content
PHP for Beginners
CHAPTER 12 Beginner

PHP Forms Handling

Updated: May 12, 2026
25 min read

# Chapter 12: PHP Forms Handling

1. Introduction

Welcome to Chapter 12! The web is interactive because of forms. Logins, registrations, search bars, and checkout processes all rely on HTML forms sending data to a server. Handling this data securely and efficiently is one of the most critical skills a backend developer must possess. In this chapter, we will build a complete form, process its submission, and learn the essential basics of validating user input so our application doesn't break when users make mistakes.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Structure a proper HTML form for data submission.
  • Capture multiple form fields in a PHP script.
  • Understand how to handle form data securely using htmlspecialchars().
  • Validate that required fields are not empty before processing.
  • Maintain form state (keep user input visible) if an error occurs.

3. The HTML Form

Let's build a basic contact form. Remember, the action attribute specifies *where* the data goes, and the method specifies *how* it goes (usually POST for sensitive data). If action is empty, it submits to the same page.
html
123456
<form action="" method="POST">
    Name: <input type="text" name="name"><br><br>
    Email: <input type="email" name="email"><br><br>
    Message: <textarea name="message"></textarea><br><br>
    <button type="submit">Send</button>
</form>

4. Processing the Form

When the user clicks "Send", the data is bundled into the $_POST array using the name attributes as keys.
php
123456789
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];
    
    echo "Thank you $name, we received your message!";
}
?>

5. Security Basics: Sanitization

Never trust user input. If a malicious user types <script>alert('Hacked!');</script> into your form, and you simply echo it back, their code will execute in your browser (This is called an XSS attack). To prevent this, always sanitize output using htmlspecialchars().
php
1234
<?php
// Converts special characters to HTML entities so they print as plain text
$safe_name = htmlspecialchars($_POST["name"]);
?>

6. Validation Basics

Validation ensures the data is correct *before* we try to use it (like saving it to a database). The simplest validation is checking if a field is empty using the empty() function.
php
1234567891011
<?php
$error = "";

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

7. Real-World Examples

When you fail to fill out a required field on a modern website, the page reloads, shows an error in red, but keeps what you already typed. This is called maintaining state.
html
12
<!-- Maintaining State using the PHP variable as the value -->
<input type="text" name="name" value="<?php echo isset($name) ? $name : &#039;'; ?>">

*The isset() function checks if a variable exists. If it does, we echo it into the value attribute.*

8. Output Explanations

In the state maintenance example, the ternary operator ? : checks if $name exists. If the user previously submitted "John", the HTML generated will be <input type="text" name="name" value="John">. If it is their first time loading the page, it outputs an empty string value="".

9. Common Mistakes

  • Forgetting htmlspecialchars: Directly echoing $_POST['data'] is a massive security flaw.
  • Validating only with HTML: Using <input required> is great for UX, but users can bypass it easily by editing the browser HTML. You must validate in PHP as well.
  • Accessing $_POST unconditionally: If you try to access $_POST['name'] on a fresh page load (a GET request), PHP throws an "Undefined array key" warning. Always wrap form logic inside if ($_SERVER["REQUEST_METHOD"] == "POST").

10. Best Practices

  • Check if the request is a POST request.
  • Check if the data is empty.
  • Sanitize the data.
  • Only then process or save the data.

11. Exercises

  1. 1. Build a form with a single "Age" input.
  1. 2. Validate that the age is not empty. If it is empty, echo an error. If it is filled, echo the age securely.

12. Mini Project: Secure Contact Form

Task: Build a contact form that validates input, displays specific errors, sanitizes data, and maintains state so the user doesn't lose their data on error.
php
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
<?php
// Initialize variables to prevent errors on first load
$name = $email = $message = "";
$nameErr = $emailErr = "";
$success_msg = "";

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

    // Validate Email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required.";
    } else {
        $email = htmlspecialchars($_POST["email"]);
    }

    // If no errors, process the form
    if (empty($nameErr) && empty($emailErr)) {
        $message = htmlspecialchars($_POST["message"]);
        $success_msg = "Form submitted successfully, $name!";
        
        // Clear variables so the form resets
        $name = $email = $message = ""; 
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <style> .error { color: red; } .success { color: green; font-weight: bold; } </style>
</head>
<body>
    <h2>Contact Us</h2>
    
    <?php if ($success_msg) echo "<p class=&#039;success'>$success_msg</p>"; ?>

    <form action="" method="POST">
        Name: <br>
        <input type="text" name="name" value="<?php echo $name; ?>">
        <span class="error">* <?php echo $nameErr; ?></span><br><br>

        Email: <br>
        <input type="email" name="email" value="<?php echo $email; ?>">
        <span class="error">* <?php echo $emailErr; ?></span><br><br>

        Message: <br>
        <textarea name="message"><?php echo $message; ?></textarea><br><br>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

13. Coding Challenges

Challenge 1: Modify the Mini Project to include a "Subject" dropdown (<select>). Ensure that you validate it is not empty, and securely capture the submitted subject.

14. MCQs with Answers

1. Why shouldn't you rely solely on HTML validation (like the required attribute)? A) Browsers do not support it. B) Malicious users can easily bypass frontend HTML validation. Backend PHP validation is mandatory for security. C) It slows down the webpage. D) It only works on mobile devices. *Answer: B*

2. Which function converts harmful HTML tags (like <script>) into harmless plain text? A) strip_tags() B) htmlspecialchars() C) secure_string() D) text_only() *Answer: B*

3. What does empty() do? A) Deletes a variable from memory. B) Empties an array. C) Checks if a variable has no value, is NULL, or is zero. D) Clears the HTML form visually on the screen. *Answer: C*

15. Interview Questions

Q: What is XSS and how do you prevent it in PHP? *A:* Cross-Site Scripting (XSS) is a vulnerability where attackers inject malicious JavaScript into web pages viewed by other users. In PHP, you prevent it by sanitizing any user-supplied data before outputting it to the browser using htmlspecialchars(), which converts executable HTML/JS tags into harmless string entities.

Q: How do you maintain the state of an input field after a form validation fails? *A:* By setting the HTML value attribute of the input field to echo the previously submitted PHP variable (e.g., <input value="<?php echo $name; ?>">). If validation fails, the page reloads but the user's previously typed text reappears, improving user experience.

16. FAQs

Q: How do I send an actual email with the form data? *A:* Once validated, you can use PHP's built-in mail() function, or better yet, a professional library like PHPMailer to securely connect to an SMTP server and send the email.

17. Summary

You have built a robust frontend-to-backend connection! You learned how to capture form data using $_POST, validate that the user actually filled it out using empty(), secure it against attacks using htmlspecialchars(), and maintain a professional user experience by preserving form state on errors.

18. Next Chapter Recommendation

We used POST for our contact form, but what if we are building a search bar? In Chapter 13: PHP GET and POST Methods, we will explore the critical differences between the two methods and when to use each!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·