English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to use PHP filters to clean and validate form data.
As you saw in the previous tutorial, the process of capturing and displaying submitted form data is very simple. In this tutorial, you will learn how to implement a simple contact form on your website that allows users to send comments and feedback via email. We will use the samePHP mail() functionto send email.
We will also implement some basic security features, such as cleaning and validating user input content, to prevent users from inserting harmful data that could compromise website security or potentially harm the application.
Below is our multi-purpose PHP script that performs the following operations:
It will ask the user to enter his comments about the website.
The same script displays the contact form and handles submitted form data.
The script cleans and validates user input. If any required fields (marked*), or due to incorrect input causing validation failure, the script will redisplay the form and display an error message for the corresponding form field.
The script will remember the fields the user has filled in and pre-fill these fields when the form is redisplayed due to validation errors.
If the user's submitted data is acceptable and everything goes smoothly, it will send an email to the website administrator and display a success message to the user.
Enter the following code in the 'contact.php' file and save it in the root directory of the project:
<?php //Function to filter user input function filterName($field) { //Clean up username $field = filter_var(trim($field), FILTER_SANITIZE_STRING); //Verify username if (filter_var($field, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z\s]+$/")))){ return $field; } else{ return FALSE; } } function filterEmail($field) { //Clean up email address $field = filter_var(trim($field), FILTER_SANITIZE_EMAIL); // Verify email address if (filter_var($field, FILTER_VALIDATE_EMAIL)) { return $field; } else{ return FALSE; } } function filterString($field) {}} // Sanitize string $field = filter_var(trim($field), FILTER_SANITIZE_STRING); if(!empty($field)){ return $field; } else{ return FALSE; } } //Define variables and initialize them with empty values $nameErr = $emailErr = $messageErr = ""; $name = $email = $subject = $message = ""; //Process form data when submitting a form if($_SERVER["REQUEST_METHOD"] == "POST"){ // Verify username if(empty($_POST["name"])){ $nameErr = "Please enter your name."; } else{ $name = filterName($_POST["name"]); if($name == FALSE){ $nameErr = "Please enter a valid name."; } } // Verify email address if(empty($_POST["email"])){ $emailErr = "Please enter your email address."; } else{ $email = filterEmail($_POST["email"]); if($email == FALSE){ $emailErr = "Please enter a valid email address."; } } // Validate message subject if(empty($_POST["subject"])){ $subject = ""; } else{ $subject = filterString($_POST["subject"]); } // Verify user comment if(empty($_POST["message"])){ $messageErr = "Please enter your comment."; } else{ $message = filterString($_POST["message"]); if($message == FALSE){ $messageErr = "Please enter a valid comment."; } } //Check for input errors before sending an email if(empty($nameErr) && empty($emailErr) && empty($messageErr)){ // Recipient email address $to = '[email protected]'; // Create email headers $headers = 'From: 'Reply-To: 'X-Mailer: PHP/' . phpversion(); // Sending email if(mail($to, $subject, $message, $headers)){ echo '<p class="success">Your message has been successfully sent!';/p>'; } else{ echo '<p class="error">Unable to send email. Please try again!';/p>'; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8> <title>Contact Form</title> <style type="text/css"> .error{ color: red; } .success{ color: green; } </style> </head> <h2>Contact Us</h2> <p>Please fill out this form and send it to us</p> <form action="contact.php" method="post"> <p> <label for="inputName">Name:</sup>*</sup></label> <input type="text" name="name" id="inputName" value="<?php echo $name; ?>"> <span class="error"><?php echo $nameErr; ?>/span> </p> <p> <label for="inputEmail">Email:</sup>*</sup></label> <input type="text" name="email" id="inputEmail" value="<?php echo $email; ?>"> <span class="error"><?php echo $emailErr; ?>/span> </p> <p> <label for="inputSubject">Subject:</label> <input type="text" name="subject" id="inputSubject" value="<?php echo $subject; ?>"> </p> <p> <label for="inputComment">Message:<sup>*</sup></label> <textarea name="message" id="inputComment" rows="5" cols="30><?php echo $message; ?>/textarea> <span class="error"><?php echo $messageErr; ?>/span> </p> <input type="submit" value="Send"> <input type="reset" value="Reset"> </form> </html>
You might be thinking of the full meaning of this code. Alright, let's dive right in.
The filterName() function validates whether the input value is a person's name. Valid names can only contain letter characters (a-z, A-Z).
The filterEmail() function validates input values as email addresses.
The filterString() function cleans input values by removing HTML tags and special characters. It does not validate any input values.
inside the<form>The attribute action="contact.php" in the <form> tag specifies the same contact.php file to display the form and handle form data.
<input>and<textarea>attribute PHP code, such as <?php echo $name; ?> when the form validation error is re-displayed, displaying the pre-filled value.
.error class PHP code, such as <span class="error"><?php echo $nameErr; ?>/>Display the error for the corresponding field.
For more information on cleaning and validating filters, please refer toPHP FiltersReference.
Note:You need to set up the mail server on your computer for the PHP mail() function to work properly. If you only want to perform form validation, you can replace the email part with your own custom code.