Form Complete in PHP
? Complete Form Handling in PHP
Let's go through creating a complete form in PHP, where we:
Sanitize and validate form inputs.
Handle form submission.
Display error messages if inputs are invalid.
Submit data to the server.
Steps:
Create an HTML form
Sanitize and validate inputs in PHP
Display success or error messages
1. HTML Form
Here's the form where users input their data:
<!-- form.html --><form action="form.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>Form Explanation:
The form uses
method="post"to submit data securely.The required attribute on inputs ensures the fields must be filled before submission.
2. PHP Script for Handling Form Submission
Create a PHP file (form.php) to handle the submitted data:
<?php// Define 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 inputs // 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 a number"; } } // Sanitize Website URL 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 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 show form and error messages --><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="text" 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
Input sanitization:
The
sanitize_input()function removes unwanted characters from inputs (trims spaces, removes slashes, converts special characters to HTML entities).
Input validation:
Name is validated to allow only letters and spaces.
Email is validated with
FILTER_VALIDATE_EMAIL.Age is validated as an integer with
FILTER_VALIDATE_INT.Website is validated as a valid URL with
FILTER_VALIDATE_URL.
Error messages:
If there's a validation error, an error message is displayed next to the corresponding field.
Form handling:
After successful validation, the form data is displayed on the screen.
4. Form Submission and Result
When the user submits the form:
If there are validation errors, the user will be shown the corresponding error message next to the form field.
If everything is valid, the form data is displayed on the screen.
? Security Considerations
Always sanitize and validate user input to protect against XSS, SQL Injection, and other security risks.
Use
htmlspecialchars()to convert special characters like<and>to HTML entities, preventing XSS attacks.Never trust user input—always validate and sanitize before processing.