Latest web development tutorials

PHP Form Validation

This chapter explains how to use our PHP form data submitted by the client validation.

PHP Form Validation

Note In dealing with PHP form we need to consider security.

This chapter we will show you PHP Form Processing data security, in order to prevent hackers and spam we need to secure the form data validation.

HTML form described in this section contains the following input fields: must be used with the optional text fields, radio buttons, and submit buttons:

View Code >>

Above form validation rules are as follows:

Field Validation rules
first name have to. + Only contain letters and spaces
E-mail have to. + Must be a valid email address (including '@' and '.')
Site have to. If present, it must contain a valid URL
Remark have to. Multi-line input field (text field)
gender have to. You must select a

First, let us look at the plain HTML form code:

Text field

"Name", "E-mail", and "URL" field is a text input element, the "notes" field is a textarea. HTML code 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>

single button

"Gender" field is a radio button, HTML code looks like this:

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

Form elements

HTML form code as follows:

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

Use this formmethod = "post" method to submit data.

Note What is $ _SERVER [ "PHP_SELF"] variables?

$ _SERVER [ "PHP_SELF"] is a super global variable, returns the currently executing script file name associated with the document root.

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

Note What is htmlspecialchars () method?

htmlspecialchars () function to some predefined characters into HTML entities.

The predefined characters are:

  • & (Ampersand) becomes & amp;
  • "(Double quote) becomes & quot;
  • '(Single quote) becomes & # 039;
  • <(Less than) becomes & lt;
  • > (Greater than) becomes & gt;

PHP form required to cause attention to where?

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

When hackers using cross-site scripting HTTP link to attack, $ _ SERVER [ "PHP_SELF"] variable will be implanted in the server script. The reason is that cross-site scripting executable file is attached to the path behind, so $ _SERVER [ "PHP_SELF"] string will contain HTTP links behind the JavaScript code.

Note XSS also known as CSS (Cross-Site Script), cross-site scripting attacks. A malicious attacker to insert malicious Web page in html code, when a user browsing the page, embedded Web inside the html code will be executed to achieve the malicious user's specific purpose.

Specify the following form file named "test_form.php":

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

Now, we use the URL to submit the specified address "test_form.php", as shown in the above code is modified as follows:

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

Doing so good.

However, taking into account the user will enter the following address in your browser address bar:'hacked')%3C/script%3E

The above URL, will be interpreted as the following code and execute it:

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

Add a script tag code and add alert command. When the page loads will execute the Javascript code (the user will see a pop-up). This is just a simple example to illustrate PHP_SELF variable will be used by hackers.

Please note that any JavaScript code can be added to the <script> tag! Hackers can use this page to redirect to a server on another page, the page code file to protect malicious code, the code can be modified to obtain the user's global variables or form data.

How to avoid the $ _SERVER [ "PHP_SELF"] being exploited?

$ _SERVER [ "PHP_SELF"] by htmlspecialchars () function to avoid being exploited.

form code as follows:

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

htmlspecialchars () to some predefined characters into HTML entities. Now if the user wants to use PHP_SELF variables, the results are output as follows:

<form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

The vulnerability attempt failed!

Use PHP form data validation

First of all we have submitted data to the user () function is processed through PHP's htmlspecialchars.

When we use the htmlspecialchars () function, the user tries to submit the following text fields:


The code will not be executed, because it will be saved as HTML escape code as follows:


The code above is safe and can be displayed or insert the message in the page.

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

  1. Use PHP trim () function to remove the user input data unnecessary characters (such as: space, tab, newline).
  2. Use PHP stripslashes () function to remove the user input data backslash (\)

Let these filtering functions written in a function of our own definition, this can greatly enhance the reusability of code.

The function named test_input ().

Now, we can test_input () function to detect all of the variables in $ _POST, script code is as follows:


// 定义变量并默认设置为空值
$name = $email = $gender = $comment = $website = "";

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

Running instance »

Note that when we execute the above script, by $ _SERVER [ "REQUEST_METHOD"] to detect whether the form is submitted. If REQUEST_METHOD is POST, the form will be submitted - the data will be verified. If the form is not submitted will skip verification and displays a blank.

Use the input items in the above examples are optional, even if the user does not enter any data can be displayed properly.

In the next section we will describe how to validate data entered by the user.