PHP form validation


In this section, we'll show you how to use PHP to validate form data submitted by clients.

In PHP website development, users submit data information through form forms, and in order to avoid submitting data that is correct, complete, and secure, we need to validate PHP forms.


PHP form validation

PHP form validation We need to consider security when working with PHP forms.

In this section, we will demonstrate the safe processing of PHP form data, and we need to verify form data security to prevent hacking and spam.

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

The form validation rules above are as follows:

Field Validate the rule
Name Have to. Only letters and spaces can be included
E-mail Have to. M ust be a valid e-mail address (including ''' and '.'
Website Have to. If present, it must contain a valid URL
Comment Have to. Multi-line input field (text field)
Gender Have to. One must be selected

First let's look at pure HTML form code:


The text field

The name, email, and website fields are text input elements, and the comment field is textarea. The HTML code looks 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>

The option button

The gender field is a turn button, and the HTML code looks like this:

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

The form element

The HTML form code looks like this:

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


The form uses the method-"post" method to submit data.

PHP form validation What is _SERVER the "PHP_SELF" variable?

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

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

PHP form validation What is the htmlspecialchars() method?

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

Predefined characters are:

  • The (and number) becomes the

  • " (double quotes) becomes the samp;quot;

  • ' (single quotes) becomes the #039;

  • The (less than) becomes the

  • (Greater than) becomes



What do you need to focus on in PHP forms?

The _SERVER variable PHP_SELF "

When a hacker attacks using HTTP links across website scripts, the $_SERVER server variable PHP_SELF is also embedded in the script. The reason is that the cross-site script is attached to the path to the execution file, so the $_SERVER string ("PHP_SELF") will contain JavaScript program code after the HTTP link.

PHP form validation XSS, also known as Cross-Site Script, attacks across station scripts. A malicious attacker inserts malicious html code into a Web page, and when a user browses the page, the html code embedded in the Web is executed for the specific 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 commit address "test_form.php" and the code above is modified to look like this:

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

That would be nice to do.

However, consider that the user enters the following address in the browser address bar:


/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

In the URL above, it will be resolved to 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 allert command is added. T he Javascript code is executed when the page is loaded (the user sees a pop-up). This is just a simple example of how PHP_SELF can be exploited by hackers.

Please note that any JavaScript code can be added to the hashtag! Hackers can use this to redirect pages to another server's page, where the page code file protects malicious code that can modify global variables or obtain user form data, instances:


How do I _SERVER the use PHP_SELF the """

The _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() convert some predefined characters into HTML entities. Now if the user wants to take advantage PHP_SELF variable, the result will output as follows:

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

Failed to attempt the vulnerability!


Use PHP to validate form data

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

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

<script>location.href('http://www.w3cschool.cn')</script>

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

&lt; s cript&gt; location.href('http://www.w3cschool.cn')&lt;/script&gt;

The above code is secure and can be displayed on the page or inserted into a message.

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

  1. Use the PHP trim() function to remove unnecessary characters from user input data (e.g. spaces, tabs, line changes).

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

Next, let's write these filtered functions in a function that we define ourselves, which greatly improves the complexity of the code.

Name the function test_input ().

Now we can detect all test_input in the $_POST by using the _POST() function, as shown in the script code:

<?php
// Define the variable and set it by default to null value.
$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;
}
?>

Run an instance . . .

Note that when we execute the above script, we _SERVER the form REQUEST_METHOD be submitted with $10,000. I f REQUEST_METHOD is POST, the form will be submitted - the data will be validated. If the form is not submitted, validation is skipped and blank is displayed.

Using inputs in the above instances is optional and can be displayed normally even if the user does not enter any data.

In the next section, we'll show you how to validate the data that the user enters.