Form Handling is arguably the most critical step in web development, as it allows users to interact with your application. The process involves four stages:
- HTML Setup: Creating the form with specific input fields.
- Submission: Sending the user’s data to the server.
- Handling: Receiving and accessing the data on the PHP script.
- Validation: Checking if the data is correct, safe, and complete.
1. HTML Form Setup (method and action)
The form’s behavior is controlled by two key HTML attributes:
| Attribute | Purpose | Values |
method | Defines how the data is sent to the server. | POST (Recommended for data submission, hides data in the URL), GET (Sends data via the URL, visible to the user). |
action | Defines the PHP script that will process the data. | The path to your processing script (or left empty to submit to the same page). |
Example Form (index.html or inside index.php):
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" required><br>
E-mail: <input type="email" name="email" required><br>
Website: <input type="url" name="website"><br>
<input type="submit" name="submit" value="Submit Data">
</form>
Security Note: Using
htmlspecialchars($_SERVER["PHP_SELF"])is a security measure. It prevents Cross-Site Scripting (XSS) by ensuring that if someone injects script tags into the URL, they are rendered harmlessly as text rather than executed by the browser.
2. PHP Handling ($_POST and $_SERVER)
When the form is submitted using the POST method, PHP automatically populates the $_POST superglobal array with the form data (where the input name is the key).
To prevent errors when the page is first loaded (before the form is submitted), you must check if the form has actually been submitted.
<?php
// Define variables to hold input values and error messages
$name = $email = $website = "";
$nameErr = $emailErr = "";
// Check if the 'submit' button was pressed
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 3. Handling: Access the data
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
// 4. Validation (will be detailed below)
if (empty($name)) {
$nameErr = "Name is required.";
}
// You would continue checking and sanitizing all fields here
// ...
}
?>
3. Comprehensive Validation and Sanitization Workflow
This is the most critical part. Every field must be processed to ensure it’s valid and safe.
A. Sanitization (Cleaning the Data)
Before validation, it’s a best practice to clean the data using PHP’s trim(), stripslashes(), and htmlspecialchars() functions.
| Function | Purpose |
trim() | Removes unnecessary whitespace (spaces, tabs, newlines) from both sides of a string. |
stripslashes() | Removes backslashes added by PHP to escape quotes (e.g., O\'Malley becomes O'Malley). |
htmlspecialchars() | Converts special characters to HTML entities (e.g., < becomes <). Essential for preventing XSS attacks. |
B. Validation (Required Fields and Format)
The PHP script below integrates handling, sanitization, and validation for required fields, email, and URL format checks.
<?php
$name = $email = $website = "";
$nameErr = $emailErr = $websiteErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// --- 1. Validate Name (Required Field) ---
if (empty($_POST["name"])) {
$nameErr = "Name is required.";
} else {
$name = clean_input($_POST["name"]);
}
// --- 2. Validate Email (Required + Format Check) ---
if (empty($_POST["email"])) {
$emailErr = "Email is required.";
} else {
$email = clean_input($_POST["email"]);
// Use the filter_var() function for robust format validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format.";
}
}
// --- 3. Validate Website (Optional + Format Check) ---
if (!empty($_POST["website"])) {
$website = clean_input($_POST["website"]);
// Use the filter_var() function for robust format validation
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$websiteErr = "Invalid URL format.";
}
}
}
// --- Reusable Sanitization Function ---
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// --- Example Output ---
if ($nameErr == "" && $emailErr == "" && $_SERVER["REQUEST_METHOD"] == "POST") {
echo "<h1>Validation Successful!</h1>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
}
?>
C. Displaying Errors in the Form
For a good user experience, the form should be displayed again, pre-filled with the user’s correct input, and showing the error messages next to the failed fields.
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span class="error">* <?php echo $nameErr; ?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email; ?>">
<span class="error">* <?php echo $emailErr; ?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website; ?>">
<span class="error"><?php echo $websiteErr; ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
