PHP Form Validation
In this chapter, we will introduce how to use PHP to validate form data submitted by the client.
PHP Form Validation
![]() |
When processing PHP forms, we need to consider security.
In this chapter, we will demonstrate secure handling of PHP form data. To prevent hackers and spam, we need to perform security validation on the form. |
|---|
The HTML form introduced in this chapter contains the following input fields: required and optional text fields, radio buttons, and a submit button:
The validation rules for the above form are as follows:
| Field | Validation Rules |
|---|---|
| Name | Required. + Can only contain letters and spaces |
| Required. + Must be a valid email address (containing '@' and '.') | |
| URL | Optional. If present, it must contain a valid URL |
| Remarks | Optional. Multi-line input field (textarea) |
| Gender | Required. Must select one |
First, let's look at the pure HTML form code:
Text Fields
The "Name", "E-mail", and "URL" fields are text input elements, and the "Remarks" field is a textarea. The HTML code is as follows:
“名字”: <input type="text" name="name"> E-mail: <input type="text" name="email"> 网址: <input type="text" name="website"> 备注: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The "Gender" field is radio buttons. The HTML code is as follows:
性别: <input type="radio" name="gender" value="female">女 <input type="radio" name="gender" value="male">男
Form Elements
The HTML form code is as follows:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
This form usesmethod="post"method to submit data.
![]() |
What is the $_SERVER["PHP_SELF"] variable? $_SERVER["PHP_SELF"] is a superglobal variable that returns the filename of the currently executing script, relative to the document root. |
|---|
So, $_SERVER["PHP_SELF"] sends form data to the current page instead of jumping to a different page.
![]() |
What is the htmlspecialchars() method? The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are:
|
|---|
What needs attention in PHP forms?
The $_SERVER["PHP_SELF"] variable can potentially be used by hackers!
When hackers use cross-site scripting HTTP links to attack, the $_SERVER["PHP_SELF"] server variable can also be injected with scripts. The reason is that the cross-site script is appended to the path of the executing file, so the $_SERVER["PHP_SELF"] string will contain JavaScript code following the HTTP link.
![]() |
XSS is also called CSS (Cross-Site Script), a cross-site scripting attack. Malicious attackers insert malicious HTML code into web pages. When users browse the page, the HTML code embedded in the web page will be executed, thereby achieving the malicious user's special purpose. |
|---|
Specify the following form file name as "test_form.php":
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Now, we use the URL to specify the submission address "test_form.php". The above code is modified as follows:
<form method="post" action="test_form.php">
That would be fine.
However, consider that users may enter the following address in the browser address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E
In the above URL, it will be parsed as the following code and executed:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
The code adds a script tag and an alert command. When the page loads, this JavaScript code will be executed (the user will see a pop-up box). This is just a simple example to illustrate that the PHP_SELF variable can be exploited by hackers.
Please note,Any JavaScript code can be added in the <script> tag!Hackers can use this to redirect the page to a page on another server. The page code file can contain malicious code, and the code can modify global variables or obtain the user's form data.
How to avoid $_SERVER["PHP_SELF"] being exploited?
The $_SERVER["PHP_SELF"] variable can be protected from exploitation using the htmlspecialchars() function.
The form code is as follows:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
htmlspecialchars() converts some predefined characters to HTML entities. Now if users want to exploit the PHP_SELF variable, the result will be output as follows:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>">
Attempting the vulnerability fails!
Using PHP to Validate Form Data
First, we process all user-submitted data through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function, if the user attempts to submit the following text field:
<script>location.href('http://www.example.com')</script>
The code will not be executed because it will be saved as HTML-escaped code, as follows:
<script>location.href('http://www.example.com')</script>
The above code is safe and can be displayed normally on the page or inserted into emails.
When the user submits the form, we will do the following two things:
- Use the PHP trim() function to remove unnecessary characters from user input data (such as spaces, tabs, newlines).
- Use the PHP stripslashes() function to remove backslashes (\) from user input data.
Next, let's write these filtering functions into a function of our own, which can greatly improve code reusability.
Name the function test_input().
Now, we can use the test_input() function to check all variables in $_POST. The script code is as follows:
Example
Run Example »
Note that when executing the above script, we use $_SERVER["REQUEST_METHOD"] to detect whether the form has been submitted. If REQUEST_METHOD is POST, the form will be submitted - and the data will be validated. If the form is not submitted, validation will be skipped and blanks will be displayed.
In the above example, all input fields are optional. Even if users do not enter any data, it will display normally.
In the following chapters, we will introduce how to validate the data entered by users.
Other Extensions