PHP Form Validation
- Previous Page PHP Form Handling
- Next Page PHP Required Form Fields
This section and the next section explain how to use PHP to validate form data.
PHP Form Validation
Tip:Pay attention to security when handling PHP forms!
These pages will demonstrate how to securely handle PHP forms. Proper validation of HTML form data is important for preventing hackers and spam!
The HTML forms we will use later contain various input fields: required and optional text fields, radio buttons, and a submit button:
The form above uses the following validation rules:
Field | Validation Rules |
---|---|
Name | Required. It must contain letters and spaces. |
Required. It must contain a valid email address (including @ and .). | |
Website | Optional. If filled out, it must contain a valid URL. |
Comment | Optional. A multi-line input field (text box). |
Gender | Required. An option must be selected. |
First, let's take a look at the pure HTML code for this form:
Text fields
The name, email, and website fields are text input elements, and the comment field is a text box. The HTML code is as follows:
Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> Website: <input type="text" name="website"> Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio buttons
The gender field is a radio button, the HTML code is as follows:
Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male
Form elements
The HTML code for the form is as follows:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
When submitting this form, form data is sent using method="post".
What is the $_SERVER["PHP_SELF"] variable?
$_SERVER["PHP_SELF"] is a superglobal variable that returns the filename of the currently executing script.
Therefore, $_SERVER["PHP_SELF"] sends form data to the current page itself, rather than redirecting to another page. This way, users can receive error messages on the form page.
What is the htmlspecialchars() function?
The htmlspecialchars() function converts special characters to HTML entities. This means that HTML characters like < and > will be replaced with < and >. This can prevent attackers from exploiting code by injecting HTML or JavaScript code (cross-site scripting attack) into the form.
Important tips on PHP form security
The $_SERVER["PHP_SELF"] variable can be exploited by hackers!
If your page uses PHP_SELF, users can input an underscore and then execute cross-site scripting (XSS).
Tip:Cross-site scripting (XSS) is a type of computer security vulnerability commonly found in web applications. XSS allows an attacker to input client-side scripts into web pages viewed by other users.
Suppose we have a page named "test_form.php" with the following form:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Now, if the user enters the normal URL in the address bar: "http://www.example.com/test_form.php", the above code will be converted to:
<form method="post" action="test_form.php">
Up to now, everything is normal.
However, if the user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
In this case, the above code will be converted to:
<form method="post" action="test_form.php"/><script>alert('hacked')</script>
This code adds a script and a prompt command. And when this page is loaded, the JavaScript code will be executed (the user will see a prompt box). This is just a simple and harmless example of how the PHP_SELF variable is used.
You should be aware that The <script> tag can contain any JavaScript code!Hackers can redirect users to a file on another server, which contains malicious code that can change global variables or submit forms to other addresses to save user data, etc.
How to prevent the exploitation of $_SERVER["PHP_SELF"]?
Using the htmlspecialchars() function can prevent the exploitation of $_SERVER["PHP_SELF"].
The form code is like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The htmlspecialchars() function converts special characters to HTML entities. Now, if the user tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>">
Inusable, no harm!
PHP form data validation
The first thing we need to do is pass all variables through PHP's htmlspecialchars() function.
After we use the htmlspecialchars() function, if the user tries to submit the following content in a text field:
<script>location.href('http://www.hacked.com')</script>
- The code will not be executed because it will be saved as escaped code, like this:
<script>location.href('http://www.hacked.com')</script>
Now this code is safe to display on the page or in an email.
When the user submits the form, we also need to do two things:
- (By using PHP trim() function) remove unnecessary characters from user input data (extra spaces, tabs, new lines, etc.)
- (By using PHP stripslashes() function) remove backslashes (\) from user input data
Next, we create a check function (this is more efficient than writing code repeatedly).
We name the function test_input().
Now, we can check each $_POST variable through the test_input() function, the script is like this:
Example
<?php // Define variables and set them to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
Please note that at the beginning of the script, we checked whether the form was submitted using $_SERVER["REQUEST_METHOD"]. If REQUEST_METHOD is POST, then the form has been submitted - and it should be validated. If not submitted, skip the validation and display a blank form.
However, in the above example, all input fields are optional. Even if the user does not enter any data, the script can still run normally.
The next step is to create required input fields and create error messages to be used when needed.
- Previous Page PHP Form Handling
- Next Page PHP Required Form Fields