PHP complete se...LOGIN
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP form validation



In this chapter we will introduce how to use PHP to verify form data submitted by the client.


PHP Form Validation

Note##We need to consider security when dealing with 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 used with optional text fields, radio buttons, and submit buttons:

1021.png

Example

<!DOCTYPE HTML> 
<html>
<head>
<meta charset="utf-8">
<title>PHP中文网(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;
}
?>

<h2>PHP 表单验证实例</h2>
<p><span class="error">* 必需字段。</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
   名字: <input type="text" name="name" value="<?php echo $name;?>">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   E-mail: <input type="text" name="email" value="<?php echo $email;?>">
   <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   网址: <input type="text" name="website" value="<?php echo $website;?>">
   <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   备注: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
   <br><br>
   性别:
   <input type="radio" name="gender" <?php if (isset($gender)&&$gender=="female") echo "checked";?>  value="female">女
   <input type="radio" name="gender" <?php if (isset($gender)&&$gender=="male") echo "checked";?>  value="male">男
   <span class="error">* <?php echo $genderErr;?></span>
   <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>
</html>

Run Instance»Click the "Run Instance" button to view the online instance

The above form validation rules are as follows:

##FieldNameE-mailURLRemarksGenderFirst let’s look at the pure HTML form code:
Validation Rules
Required. +Can only contain letters and spaces
Required. + Must be a valid email address (contains '@' and '.')
Required. If present, it must contain a valid URL
Required. Multi-line input field (text field)
Required. You must select a

Text field

"Name" , "E-mail", and "Website" fields are text input elements, and the "Remarks" field is 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 button

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

Gender :
<input type="radio" name="gender" value="female">女
<input type="radio" name="gender" value="male">男

Form elements

HTML form code is as follows:

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

So, $_SERVER["PHP_SELF"] will send the form data to the current page instead of jumping to a different page.

Note $_SERVER["PHP_SELF"] is a super global variable that returns the file name of the currently executing script and is related to the document root.

##XSS is also called CSS (Cross-Site Script), 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.
Note##What is the htmlspecialchars() method?
htmlspecialchars() function converts some preset The defined characters are converted into HTML entities.
The predefined characters are:

    ##& (ampersand) becomes &
  • ##" (double quotation marks) becomes "
  • ' (single quote) becomes '
  • ##< (less than) becomes <

  • > (Greater than) Become an area that requires attention in the PHP form?

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



Specify the following form file name "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, 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
, the above URL will be parsed into the following code and executed:
<form method="post" action="test_form.php/"><script>alert('hacked')</script>
added a script tag to the code and added an alert command. 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's page. Malicious code can be protected in the code file, and 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 looks like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
htmlspecialchars() Converts some predefined characters into HTML entities. Now if the user wants to take advantage of 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, when the user tries to submit the following text field:

<script>location.href('http://www.php.cn')</script>
the code will not be executed because it will be saved as HTML escape The code is as follows:
<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. 1. Use the PHP trim() function to remove irrelevant information from the user input data. Necessary characters (such as spaces, tabs, newlines).

  2. 2. Use the PHP stripslashes() function to remove backslashes (\) from user input data

Next let’s add these The filtering function is written in a function defined by 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

<!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="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>

Run Instance»

Click the "Run Instance" button to view the online instance

Note that 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.

Recommended practical tutorials: "PHP Form Validation"

In the next chapter we will introduce how to perform verification on the data entered by the user. verify.

php.cn