Handling HTML Forms in PHP: Methods, Controls & Validation
Study Deep: Form Security Best Practices
When handling forms in a University exam or professional project, security is as important as functionality.
- Cross-Site Scripting (XSS) Prevention: Always use
htmlspecialchars()when displaying user-submitted data to prevent malicious scripts from executing in the browser. - CSRF Protection: Use hidden tokens to ensure that form submissions originate from your own site.
- Empty Field Checks: Never assume a user will fill out all fields. Always use
empty()orisset()before processing. - Data Sanitization: Use
trim()to remove accidental whitespace andstripslashes()to clean up data.
1. What is an HTML Form?
An HTML Form is a section of a web page that contains interactive controls (text boxes, checkboxes, buttons, etc.) allowing users to input data and submit it to a web server for processing.
Key Form Attributes:
| Attribute | Purpose | Example |
|---|---|---|
action | Specifies the URL of the PHP script that will process the form data | action="process.php" |
method | Specifies how data is sent: GET or POST | method="post" |
enctype | Required for file uploads: multipart/form-data | enctype="multipart/form-data" |
2. Form Handling Process (Step-by-Step)
- Design: HTML form is created with appropriate input controls.
- User Input: The user fills in the form fields in the browser.
- Submission: User clicks the Submit button.
- HTTP Request: The browser packages the form data and sends it to the server URL specified in
action. - PHP Processing: The PHP script reads values from
$_GETor$_POST. - Validation: PHP checks that the data is correct and complete.
- Response: After processing (saving, emailing, etc.), PHP sends back an HTML response page.
3. GET vs POST Methods — Detailed Comparison
| Feature | GET Method | POST Method |
|---|---|---|
| Visibility | Data visible in URL (e.g., page.php?name=Rohit) | Data hidden from URL bar |
| Security | Low — NEVER use for passwords or sensitive data | Higher — data sent in HTTP request body |
| Data Limit | Limited (~2000 characters) | No practical limit — can send large files |
| Caching | Can be cached and bookmarked | Cannot be cached or bookmarked |
| Data Type | Only ASCII characters | Binary data allowed (images, documents) |
| Browser History | URL (with data) is stored in history | Data NOT stored in browser history |
| Idempotent | Yes (safe to repeat) | No (repeated submission = repeated action) |
| Best Used For | Fetching data (search forms, filters, pagination) | Submitting data (login, registration, file upload) |
4. A Complete Form Example
HTML File (form.html):
<form method="POST" action="process.php">
<label>Name:</label>
<input type="text" name="fname" placeholder="Enter your name"><br>
<label>Email:</label>
<input type="email" name="email" placeholder="Enter email"><br>
<label>Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
<label>Skills:</label>
<input type="checkbox" name="skills[]" value="PHP"> PHP
<input type="checkbox" name="skills[]" value="JavaScript"> JS<br>
<label>City:</label>
<select name="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
</select><br>
<textarea name="message" placeholder="Your message..."></textarea><br>
<input type="submit" value="Submit">
</form>
PHP File (process.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['fname']);
$email = htmlspecialchars($_POST['email']);
$gender = $_POST['gender'] ?? 'Not specified';
$skills = isset($_POST['skills']) ? implode(", ", $_POST['skills']) : "None";
$city = $_POST['city'];
echo "Name: $name<br>";
echo "Email: $email<br>";
echo "Gender: $gender<br>";
echo "Skills: $skills<br>";
echo "City: $city<br>";
}
?>
5. PHP Form Validation
Definition: Form validation is the process of checking that submitted form data is correct, complete, and safe before using it.
Why Validate?
- Prevent empty submissions.
- Ensure correct data format (e.g., valid email).
- Protect against malicious input (XSS attacks).
Common Validation Functions:
| Function | Purpose | Example |
|---|---|---|
empty($var) | Check if variable is empty/null | empty($_POST['name']) |
isset($var) | Check if variable is set and not null | isset($_POST['email']) |
filter_var($var, FILTER) | Validate/sanitize using a filter | filter_var($email, FILTER_VALIDATE_EMAIL) |
htmlspecialchars($str) | Convert special chars to HTML entities (prevents XSS) | htmlspecialchars($_POST['name']) |
trim($str) | Remove extra whitespace | trim($_POST['name']) |
preg_match($pattern, $str) | Match a regular expression | preg_match("/^[A-Za-z]+$/", $name) |
Complete Validation Example:
<?php
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = htmlspecialchars(trim($_POST["name"]));
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$email = htmlspecialchars(trim($_POST["email"]));
}
}
?>
6. The $_REQUEST Superglobal
$_REQUEST is a superglobal that contains the combined contents of $_GET, $_POST, and $_COOKIE. It is flexible but less secure than using specific method arrays.
// Works for BOTH GET and POST requests
$name = $_REQUEST['fname'];
When to use: Only when you genuinely need to handle both GET and POST. For most forms, use the specific $_POST or $_GET.