PHP form validation
We need to consider security when processing PHP forms.
In this chapter we will demonstrate the secure processing of PHP form data. In order to prevent hackers and spam, we need to perform data security verification on the form.
The HTML form introduced in this chapter contains the following input fields: Must be with optional text fields, radio buttons , and submit button:
Instance
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>PHP.cn</title> </head> <body> <h2>PHP 表单验证实例</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 名字: <input type="text" name="name" value=""> <br> E-mail: <input type="text" name="email" value=""> <br> 网址: <input type="text" name="website" value=""> <br> 备注: <textarea name="comment" rows="5" cols="40"></textarea> <br> 性别: <input type="radio" name="gender" value="female">女 <input type="radio" name="gender" value="male">男 <br> <input type="submit" name="submit" value="提交"> </form> </body> </html>
Program running result:
The above form validation rules are as follows:
Field | Verification rules |
Name | is required. + Can only contain letters and spaces |
is required. + Must be a valid email address (contains '@' and '.') | |
URL | Optional. If present, it must contain a valid URL |
Remarks | Optional. Multi-line input field (text field) |
Gender | Required. Must select a |
Let’s break the code apart and look at it:
Text Field
The "Name", "E-mail", and "Website" fields are text input elements, and the "Remarks" field is the text area textarea.
HTML code is as follows:
##Name: <input type=" text" name="name" value=""> E-mail: <input type="text" name="email" value="">
Website: <input type=" text" name="website" value="">
Note: <textarea name="comment" rows="5" cols="40"></textarea>
single 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
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])";?>This form uses method="post" method to submit data.
What is the $_SERVER["PHP_SELF"] variable?
$_SERVER["PHP_SELF"] is a super global variable that returns the file name of the currently executing script.
Therefore, $_SERVER["PHP_SELF"] sends the form data to the page itself instead of jumping to another page. In this way, users can get error message information on the form page.
What is the htmlspecialchars() function?
htmlspecialchars() function converts special characters into HTML entities. This means that HTML characters like < and > are replaced with < and > . This prevents attackers from exploiting the code by injecting HTML or JavaScript code into the form (cross-site scripting attacks).
Important Tips About PHP Form Security
$_SERVER["PHP_SELF"] variables can be exploited by hackers!
If your page uses PHP_SELF, users can enter an underscore and execute cross-site scripting (XSS), also known as css.
reminder: Cross-site scripting (XSS) is a computer security vulnerability type, commonly in Web applications. XSS enables an attacker to enter client-side script into web pages viewed by other users.
Suppose we have the following form in a page named "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's fine.
However, consider that the user will enter the following address in the browser address bar:
http://www.php.cn/test_form.php/%22 %3E%3Cscript%3Ealert('hacked')%3C/script%3E
The above URL will be parsed into the following code and executed:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
A script tag has been added to the code, and an alert command has been added. This Javascript code will be executed when the page loads (the user will see a pop-up box). This is just a simple example of how 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 another server. The page code file can protect malicious code. The code can modify global variables or obtain the user's form data.
How to prevent $_SERVER["PHP_SELF"] from being exploited?
##$_SERVER ["PHP_SELF"] can be avoided by using the htmlspecialchars() function. The form code is as follows:
htmlspecialchars() Convert some predefined characters into HTML entities. Now if the user wants to utilize the PHP_SELF variable, the result will be output as follows:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ;?>">
Failed to try this vulnerability!<form method="post" action="test_form.php/"><script> alert('hacked')</script>">
Validate form data via PHP
The first thing we need to do is pass all the variables through PHP's htmlspecialchars() function. After we use the htmlspecialchars() function, if the user tries to submit the following content in the text field:
- The code will not be executed because it will be saved as an escaped code, like this:<script>location.href('http:/ /www.hacked.com')</script>
<script>location.href('http://www.hacked.com')</script>Now this code is displayed on the page It is safe online or by e-mail. When the user submits the form, we have to do two more things: 1. (Through the PHP trim() function) Remove unnecessary characters (extra spaces) in the user input data , tab character, newline)2. (Through PHP stripslashes() function) Remove backslashes (\) in user input dataNext we create a check function (similar to This is more efficient than writing code over and over again). We named the function test_input(). Now, we can check each $_POST variable through the test_input() function, the script is like this:
Example
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>PHP中文网(php.cn)</title> </head> <body> <?php // 定义变量并默认设置为空值 $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; } ?> <h2>PHP 表单验证实例</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 名字: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> 网址: <input type="text" name="website"> <br><br> 备注: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女 <input type="radio" name="gender" value="male">男 <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您输入的内容是:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body>Let’s run the program and see
Note: When we execute the above script, we will 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 displayed blank.
The use of input items in the above examples is optional, and it can be displayed normally even if the user does not enter any data.
In the next chapter we will introduce how to verify the data entered by the user.