PHP form valida...LOGIN

PHP form validation

PHP Form Validation

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

User input should be validated (via client script) whenever possible. Browser validation is faster and reduces the load on the server.

If user input needs to be inserted into the database, you should consider using server validation. A good way to validate a form on the server is to pass the form to itself, rather than jumping to a different page. This way users can get error messages on the same form page. It will be easier for users to find errors.

#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.

PHP form validation example

QQ图片20161009114426.png

The above form uses the following validation rules:

QQ图片20161009114556.png

##First let’s take a look at the pure HTML code of this form:

Text field

name, email and website are text input elements, and the comment field is a text box. The HTML code is like this:

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



Radio button

gender field is single Select button, the HTML code is like this:

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male

Form element

The HTML code for the form is like this:

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

When this form is submitted, form data is sent via method="post".


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).

Tip: Cross-site scripting (XSS) is a type of computer security vulnerability that is common in web applications. XSS enables an attacker to enter client-side script into web pages viewed by other users.


Suppose we have a page named "test_form.php" with the following form:

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

Now, if the user enters the normal URL in the address bar: "http://www. php.cn/test_form.php", the above code will be converted to:

<form method="post" action="test_form.php">

So far ,everything is normal.

However, if the user types the following URL in the address bar:

//m.sbmmt.com/test_form.php/%22%3E%3Cscript%3Ealert('php ')%3C/script%3E

In this case, the above code will be converted to:

<form method="post" action="test_form.php "/><script>alert('php')</script>

This code adds a script and a prompt command. And when the page loads, the JavaScript code will be executed (the user will see a tooltip). This is just a simple and harmless example of how the PHP_SELF variable can be exploited.


You should realize that you can add any JavaScript code inside the <script> tag! Hackers can redirect users to a file on another server, and malicious code in that file can change global variables or submit a form to a different address to save user data, etc.


How to prevent $_SERVER["PHP_SELF"] from being exploited?

Using the htmlspecialchars() function can prevent $_SERVER["PHP_SELF"] from being exploited.

The form code is like this:

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

htmlspecialchars() function converts special characters into HTML entities. Now, if the user attempts to exploit the PHP_SELF variable, it will result in the following output:

<form method="post" action="test_form.php/"><script>alert('php')< /script>">

Cannot be exploited, no harm!


##Verify form data through PHP

We have to do The first thing is to pass all the variables through PHP's htmlspecialchars() function

After we use the htmlspecialchars() function, if the user tries to submit the following in the text field:

< ;script>location.href('//m.sbmmt.com')</script>


- The code will not be executed because it will be saved as an escaped code, like so:

<script>location.href('//m.sbmmt.com')</script>

Now this code is displayed on the page or in the e-mail is safe.

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 data

Next we create a check function (similar to This is more efficient than writing code over and over again).

We named the function test_input().


Next Section
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</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>
submitReset Code
ChapterCourseware