PHP Form Validation

Source: Internet
Author: User
Tags html form php form php form validation validation examples

PHP Form Validation

Tip: Pay attention to security when working with PHP forms!

These pages will show how to handle PHP forms securely. Proper validation of HTML form data is important to protect against hackers and junk mail!

The HTML form We'll use later contains a variety of input fields: required and optional text fields, radio buttons, and Submit buttons:

The above form uses the following validation rules:

First, let's look at the pure HTML code for this form:

Text field

Name, email, and website belong to the text INPUT element, and the comment field is a text box. The HTML code is this:

1Name: <input type="text"Name="name">2E-mail: <input type="text"Name="Email">3Website: <input type="text"Name="website">4Comment: <textarea name="Comment"Rows="5"cols=" +"></textarea>
radio button

The gender field is a radio button, and the HTML code is this:

 1  gender:  2  <input type= " radio   name="  gender   value="  female   >female  3  <input type= radio   " Name="  gender   " Value="  male   " >male 
Form elements

The HTML code for the form is this:

1 <form method="post" action="<?php Echo htmlspecialchars ($_ server["php_self"]);? >">

When this form is submitted, the form data is sent by method= "POST".

What is a $_server["php_self"] variable?

$_server["Php_self" is a super global variable that returns the file name of the current execution script.

Therefore, $_server["php_self"] sends form data to the page itself instead of jumping to another page. This allows the user to get an error message on the form page.

What is the Htmlspecialchars () function?

The Htmlspecialchars () function converts special characters to HTML entities. This means that HTML characters such as < and > are replaced with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or JavaScript code (cross-site scripting attacks) into the form.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------

Important tips for PHP form security

$_server["Php_self"] variables can be exploited by hackers!

If your page uses php_self, the user can enter an underscore and then perform cross-site scripting (XSS).

tip: Cross-site scripting (Cross-site SCRIPTING,XSS) is a type of computer security vulnerability that is common to Web applications. XSS enables an attacker to enter client script into a webpage that is viewed by other users.

Suppose one of our pages named "test_form.php" has the following form:

1 <form method="post" action="<?php echo $_server[" php_self"];? >">

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

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

Until now, everything is fine.

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

1 http://Www.example.com/test_form.php/%22%3E%3Cscript%3Ealert (' hacked ')%3c/script%3e

In this case, the above code is converted to:

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

This code adds a script and a hint command. And when this page loads, the JavaScript code is executed (the user will see a prompt box). This is just a simple harmless case of how php_self variables can be exploited.

You should be aware that any JavaScript code can be added to the <script> tag! Hackers can redirect users to a file on another server, where malicious code can change global variables or submit forms to other addresses to save user data, and so on.

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------

If you avoid $_server["php_self"] be exploited?

By using the Htmlspecialchars () function, you can avoid $_server["php_self" being exploited.

This is the form code:

1 <form method="post" action="<?php Echo htmlspecialchars ($_ server["php_self"]);? >">

The Htmlspecialchars () function converts special characters to HTML entities. Now, if the user tries to take advantage of the php_self variable, it causes the following output:

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

No use, no harm!

--------------------------------------------------------------------------------------------------------------- ------------------------------------------------

Validating form data with PHP

The first thing we want to do is pass all the variables through the PHP htmlspecialchars () function.

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

1 <script>location.href ('http://www.hacked.com') </script>

-The code will not execute because it will be saved as an escape code, like this:

1 &lt;script&gt;location.href ('http://www.hacked.com') &lt;/ Script&gt;

Now this code appears to be safe on the page or in an e-mail message.

When the user submits the form, there are two things we need to do:

    1. (via the PHP trim () function) removes unnecessary characters from user input data (extra spaces, tabs, line breaks)
    2. Remove backslash (\) from user input data (via PHP stripslashes () function)

Next we create a check function (which is more efficient than writing the code over and over again).

We name the function Test_input ().

Now we can examine each $_post variable through the Test_input () function, which is the script:

Instance
1<! DOCTYPE html>2345<body>6 7<?PHP8 //define variables and set to empty values9$name = $email = $gender = $comment = $website ="";Ten  One if($_server["Request_method"] =="POST") { A$name = Test_input ($_post["name"]); -$email = Test_input ($_post["Email"]); -$website = Test_input ($_post["website"]); the$comment = Test_input ($_post["Comment"]); -$gender = Test_input ($_post["Gender"]); - } -  + function Test_input ($data) { -$data =trim ($data); +$data =stripslashes ($data); A$data =Htmlspecialchars ($data); at    return$data; - } -?> -  - -<form method="Post"action="<?php Echo htmlspecialchars ($_server["Php_self"]);? >"> inName: <input type="text"Name="name"> -<br><br> toE-mail: <input type="text"Name="Email"> +<br><br> -Website: <input type="text"Name="website"> the<br><br> *Comments: <textarea name="Comment"Rows="5"cols=" +"></textarea> $<br><br>Panax Notoginseng Gender: -<input type="Radio"Name="Gender"Value="female">female the<input type="Radio"Name="Gender"Value="male">male +<br><br> A<input type="Submit"Name="Submit"Value="Submit"> the</form> +  -<?PHP $Echo""; $ echo $name; -Echo"<br>"; - echo $email; theEcho"<br>"; - echo $website;WuyiEcho"<br>"; the echo $comment; -Echo"<br>"; Wu echo $gender; -?> About  $</body> -

Operation Result:

Note that at the beginning of the script, we check to see if the form is being submitted using $_server["Request_method". If Request_method is POST, the form has been submitted-and it should be validated. If not committed, the validation is skipped and a blank form is displayed.

However, in the example above, all the input fields are optional. Even if the user does not enter any data, the script will work correctly.

The next step is to make the required input fields and create the error message to use when needed.

PHP Form Validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.