PHP Form Validation
In this chapter we will introduce how to use PHP to verify form data submitted by the client.
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 and optional text fields, radio buttons, and submit buttons:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>php.cn</title> <style> .error {color: #FF0000;} </style> </head> <body>
<?php // 定义变量并默认设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "名字是必需的"; } else { $name = test_input($_POST["name"]); // 检测名字是否只包含字母跟空格 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "邮箱是必需的"; } else { $email = test_input($_POST["email"]); // 检测邮箱是否合法 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "非法邮箱格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 检测 URL 地址是否合法 if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "非法的 URL 的地址"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必需的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
First let us look at pure HTML first Form code:
Text field
"名字", "E-mail", 及"网址"字段为文本输入元素,"备注"字段是 textarea。HTML代码如下所示: “名字”: <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 button
The "Gender" field is a radio button, HTML code As shown below:
Gender:
<input type="radio" name="gender" value="female">Female
<input type= "radio" name="gender" value="male">Male
Form elements
HTML form code is as follows Display:
<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 value of the currently executing script File name, related to document root.
So, $_SERVER["PHP_SELF"] will send the 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 into HTML entities.
stereotypes are:
# · & (Hehe) to become & amp;
· "(double quotes) to become & quot (Single quotation number) becomes '
· & lt; (less than) to become & lt;
## This · & gt; (greater than) to become & gt What needs to be paid attention to?$_SERVER["PHP_SELF"] variables may be used by hackers!
When hackers use cross-site script HTTP links to attack, The $_SERVER["PHP_SELF"] server variable will also be embedded in the script. The reason is that the cross-site script is appended to the path of the executable file, so the string of $_SERVER["PHP_SELF"] will contain the JavaScript behind the HTTP link. Program code.
##XSS is also called CSS (Cross-Site Script), a cross-site scripting attack. Malicious attackers insert malicious HTML code into the Web page. When the page is paged, the html code embedded in the Web will be executed to achieve the special purpose of the malicious user
.
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">
This is good.
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>
The script tag is added to the code and the alert command is 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 that 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 avoid $_SERVER["PHP_SELF"] from being exploited?
$_SERVER["PHP_SELF"] can be avoided by using the htmlspecialchars() function .
The form code is as follows:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> ;
htmlspecialchars() Convert some predefined characters into HTML entities. Now if the user wants to exploit the PHP_SELF variable, the result will be output as follows:
<form method="post" action="test_form.php/"><script>alert('hacked') </script>">
Failed to try this vulnerability!
Use PHP to verify form data
First of all, we process all the data submitted by the user through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function, the user tries to submit the following text field:
<script>location.href('http://www.php.cn')< ;/script>
This code will not be executed because it will be saved as HTML escaped code, as shown below:
<script>location.href('http: //www.php.cn')</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:
1. Use the PHP trim() function to remove unnecessary characters (such as spaces, tabs) in the user input data , newline).
2. Use PHP stripslashes() function to remove backslashes (\) in user input data
Next, let us write these filtering functions in a function we define ourselves, which can greatly improve the reusability of the code.
Name the function test_input().
Now, we can detect all variables in $_POST through the test_input() function. The script code is as follows:
Example
<?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; } ?>
Note that we are executing the above script When, $_SERVER["REQUEST_METHOD"] will be used 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.
1. Use the PHP trim() function to remove unnecessary characters (such as spaces, tabs, newlines) in user input data.
2. Use the PHP stripslashes() function to remove backslashes (\) in user input data
3. Use the test_input() function to detect all variables in $_POST