Form Handling in PHP
? Form Handling in PHP
Form handling in PHP involves receiving user input from an HTML form, validating the data, sanitizing it to prevent security issues, and then processing it — whether by storing it in a database, sending an email, or performing some other operation.
Let's walk through the entire process of creating, validating, and processing a form in PHP:
1. HTML Form
This is the basic HTML form that allows users to input data. It uses the POST method to securely submit the data to the server.
<!-- form.html --><form action="form-handler.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> <label for="age">Age:</label> <input type="text" id="age" name="age" required><br><br> <label for="website">Website:</label> <input type="text" id="website" name="website"><br><br> <input type="submit" value="Submit"></form>Method: The form uses
POSTso that data is sent securely.Fields: Name, email, age, and website are the fields that the user fills out.
2. PHP Script for Handling Form Submission
The data sent via POST is handled by a PHP script (form-handler.php). It sanitizes, validates, and displays the results.
<?php// Initialize variables and set to empty values$name = $email = $age = $website = "";$nameErr = $emailErr = $ageErr = $websiteErr = "";// Check if form is submittedif ($_SERVER["REQUEST_METHOD"] == "POST") { // Sanitize and validate Name if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = sanitize_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/", $name)) { $nameErr = "Only letters and white space allowed"; } } // Sanitize and validate Email if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = sanitize_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } // Sanitize and validate Age if (empty($_POST["age"])) { $ageErr = "Age is required"; } else { $age = sanitize_input($_POST["age"]); if (!filter_var($age, FILTER_VALIDATE_INT)) { $ageErr = "Age must be an integer"; } } // Sanitize Website if (!empty($_POST["website"])) { $website = sanitize_input($_POST["website"]); if (!filter_var($website, FILTER_VALIDATE_URL)) { $websiteErr = "Invalid URL format"; } } // If no errors, display success message if (empty($nameErr) && empty($emailErr) && empty($ageErr) && empty($websiteErr)) { echo "<h2>Success! Form Submitted:</h2>"; echo "Name: $name<br>"; echo "Email: $email<br>"; echo "Age: $age<br>"; echo "Website: $website<br>"; }}// Function to sanitize user inputfunction sanitize_input($data) { $data = trim($data); // Remove extra spaces $data = stripslashes($data); // Remove backslashes $data = htmlspecialchars($data); // Convert special characters to HTML entities return $data;}?><!-- HTML to display form and errors --><h2>PHP Form Validation</h2><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> Name: <input type="text" name="name" value="<?php echo $name; ?>"> <span><?php echo $nameErr; ?></span><br><br> Email: <input type="email" name="email" value="<?php echo $email; ?>"> <span><?php echo $emailErr; ?></span><br><br> Age: <input type="text" name="age" value="<?php echo $age; ?>"> <span><?php echo $ageErr; ?></span><br><br> Website: <input type="text" name="website" value="<?php echo $website; ?>"> <span><?php echo $websiteErr; ?></span><br><br> <input type="submit" value="Submit"></form>3. Explanation of the PHP Script
Sanitizing User Input:
The function
sanitize_input()is used to clean user input by:Removing extra spaces (
trim()).Stripping slashes (
stripslashes()).Converting special characters to HTML entities (
htmlspecialchars()).
Validating the Input:
Name: Ensures the name only contains letters and spaces using a regular expression (
preg_match()).Email: Uses
filter_var()withFILTER_VALIDATE_EMAILto ensure the email is in a valid format.Age: Validates that the age is an integer using
filter_var()withFILTER_VALIDATE_INT.Website: Validates the URL format using
FILTER_VALIDATE_URL.
Error Handling:
If the input is invalid, an appropriate error message is displayed next to the form field.
If all inputs are valid, the form data is displayed on the page.
4. Security Considerations
Sanitize all user input to protect against Cross-Site Scripting (XSS) and other attacks.
Always validate input to ensure data is in the expected format.
Use
htmlspecialchars()to escape special characters and prevent malicious code execution.
5. Displaying Success/Failure
Success: When the form data passes validation, a confirmation message is displayed with the sanitized values.
Error: If there are validation issues, the user will see specific error messages next to the fields.
6. Extending the Example
Database Integration: You can extend this by storing the form data in a database, such as MySQL, after sanitizing and validating the inputs.
File Uploads: Add file upload functionality by validating and handling file inputs securely.