PHP Forms Handling
# 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, theaction 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.
4. Processing the Form
When the user clicks "Send", the data is bundled into the$_POST array using the name attributes as keys.
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().
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 theempty() function.
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.*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
$_POSTunconditionally: 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 insideif ($_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. Build a form with a single "Age" input.
- 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.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 therequired 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 usinghtmlspecialchars(), 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-inmail() 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.