PHP form validation


HTML Form Validation

When the form is used to collect customer input information, do not take it for granted that the customer will input the required content as expected. Customer input must be strictly checked at all times.

Client-side verification

Client-side form verification is generally a verification method based on Javascript scripts. This verification method can effectively reduce the burden on the server and can also instantly remind customers of input errors.

Server-side verification

In some cases, in addition to client-side verification, server-side verification may also be required (such as accessing the database). At this time, logical verification needs to be done in the PHP program.

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: required and optional text fields, radio buttons, and submit buttons:

form1.jpgView Code »

The above form validation rules are as follows:

Fields                       Validation rules

#Name                                                                                + Can only contain letters and spaces

E-mail                                                                                                                                        + Must be a valid email address (contains '@' and '.')

URL                                                                                                                                                                    Required. If present, it must contain a valid URL. Multi-line input field (text field)

Gender                                                                                                                                                                              You must choose one

First let us look at the pure HTML form code:

Text field

The "Name", "E-mail", and "Website" fields are text input elements, and the "Remarks" field is a textarea. The HTML code is as follows:

"Name": <input type="text" name="name">
E-mail: <input type="text" name="email ">
            URL: <input type="text" name="website">
                      Remarks: <textarea name="comment" rows="5" cols="40">< /textarea>          

Radio button

The "Gender" field is a radio button, the HTML code is as follows:  

                                           
                                                                                                                                                                      

#Form elements

HTML form code is as follows:

          <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


This form uses the method="post" method to submit data.

What is the $_SERVER["PHP_SELF"] variable?


$_SERVER["PHP_SELF"] is a super global variable that returns the current The file name of the executed script, related to the 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. The predefined characters for

are:

& (ampersand) becomes &

" (double quotation mark) becomes "

' (single quotation mark ) become'

< (less than) become<

> (greater than) become>

Things that need attention in PHP forms Where?

##$_SERVER["PHP_SELF"] variables may be used by hackers!

When hackers use cross-site scripting HTTP links to attack, the $_SERVER["PHP_SELF"] server variable will also be embedded in the script. The reason is that cross-site scripting is appended to the path of the executable file, so the string of $_SERVER["PHP_SELF"] will contain the JavaScript program code behind the HTTP link.

XSS is also called CSS (Cross-Site Script), a cross-site scripting attack. Malicious attackers insert malicious HTML code into a Web page. When a user browses the page, the HTML code embedded in the Web page will be executed, thereby achieving the special purpose of the malicious user.

Specify the following form file name as "test_form.php":

                                                                                                                                                             <?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 ;

However, considering 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

## or above will be parsed to the following code and execute:

; FORM METHOD = "Post" action = "test_form.php/"><script>alert('hacked')</script>            


The script tag has been added to the code, and the 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 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:

                                                                                                                                                                                                                                                                                      ​;          

htmlspecialchars() Convert some predefined characters into HTML entities. Now if the user wants to take advantage of the PHP_SELF variable, the result will be output as follows:

                                                                                                                                                                                                                            ,,,,, The vulnerability failed!

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>          

This code will not be executed because it will be saved as HTML escaped code, as shown below: 'http://www.php.cn')</script>

When the user submits the form, we will do the following two things:

Use the PHP trim() function to remove unnecessary characters (such as spaces, tabs, newlines) in the user input data ).


Use the PHP stripslashes() function to remove backslashes (\) in user input data

Next let us write these filtering functions in a function we define, so It can greatly improve the reusability of code.

Name the function test_input().

Now, we can use the test_input() function to detect all variables in $_POST. 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 When the above script is executed, $_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.

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.


Continuing Learning
||
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>PHP中文网</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="Submit"> </form> <?php echo "<h2>您输入的内容是:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body>
submitReset Code