WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 Form Validation


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


PHP form validation

Note We need to consider security when processing PHP forms.

In this chapter, we will show the secure processing of PHP form data. In order to prevent hackers and spam, we need to verify the data security of the form.

The following input fields are included in the HTML forms described in this section: Must be with optional text fields, radio buttons, and submit buttons:

The above form validation rules are as follows:

field Validation rules
name Required. + Can only contain letters and spaces
E-mail Required. + Must be a valid email address (including '@' and '.')
URL Optional. If it exists, it must contain a valid URL
Remarks Optional. Multi-line input field (text field)
Gender Required. Must choose one

First let's take a look at the form code in pure HTML:


Text field

The "Name", "E-mail", and "URL" fields are text input elements, and the "Remarks" field is textarea. The HTML code looks like this:

“first name”: <input type="text" name="name">
E-mail: <input type="text" name="email">
URL: <input type="text" name="website">
Note: <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">Female
<input type="radio" name="gender" value="male">male

Form elements

The HTML form code looks like this:

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

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

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

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

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

Note What is htmlspecialchars () method?

The htmlspecialchars () function converts some predefined characters into HTML entities.

The predefined characters are:

  • & (And) become &amp;
  • " (Double quotes) become &quot;
  • ' (apostrophe) become &#039;
  • < (Less than) become &lt;
  • > (more than the) become &gt;


What needs attention in PHP forms?

The $ _SERVER ["PHP_SELF"] variable may be used by hackers!

When a hacker uses an HTTP link from a cross-site script to attack, the $ _SERVER ["PHP_SELF"] server variable is also implanted into the script. The reason is that the cross-site script is appended to the path of the execution file, so the string $ _SERVER ["PHP_SELF"] will contain the JavaScript program code behind the HTTP link.

Note XSSAlso called CSS (Cross-Site Script), cross-site scripting attack. A malicious attacker inserts malicious html code into a web page. When a user browses the page, the html code embedded in the web will be executed, thereby achieving the special purpose of the malicious user.

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

However, considering that users would enter the following address in the browser's address bar:

http://www.runoob.com/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>

The script tag is added to the code, and the alert command is added. This Javascript code is executed when the page loads (the user will see a pop-up box). This is just a simple example to show that the PHP_SELF variable will be used by hackers.

Please note, Any JavaScript code can be added in<script>In label! Hackers can use this to redirect pages to pages on another server. Pages The code file can protect malicious code. The code can modify global variables or obtain user form data.


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

$ _ SERVER ["PHP_SELF"] can be avoided by using the htmlspecialchars () function.

form The code is shown below:

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

htmlspecialchars () converts some predefined characters to HTML entities. Now if users want to use PHP_SELF variable, the result will be as follows:

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

Failed to try the vulnerability!


Validate form data using PHP

First of all, all data submitted by users are processed by PHP's htmlspecialchars () function.

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

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

The code will not be executed because it will be saved as HTML escape code as shown below:

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

The above code is safe and can be displayed on the page or inserted into the email normally.

When a user submits a form, we will do two things:

  1. Use the PHP trim () function to remove unnecessary characters (such as spaces, tabs, and newlines) from user input data.
  2. Use the PHP stripslashes () function to strip backslashes (\) from user input data

Then let's write these filtered functions in a function we define ourselves, which can greatly improve the reusability of the code.

Name the function test_input ().

Now, we can test all variables in $ _POST through the test_input () function. The script code is as follows:

Example

<?php // Define a variable and set it to null by default $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 when we execute the above script, we will check if the form is submitted through $ _SERVER ["REQUEST_METHOD"] . If REQUEST_METHOD is POST, the form will be submitted-the data will be validated. If the form is not submitted, validation will be skipped and displayed blank.

In the above example, the use of input items is optional, and can be displayed normally even if the user does not enter any data.

In the following sections, we will introduce how to validate the data entered by the user.