Easy Tutorial
❮ Func Array Intersect Uassoc Func String Mb_Strlen ❯

PHP Form Validation


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


PHP Form Validation

| | When processing PHP forms, we need to consider security. This section will demonstrate secure handling of PHP form data to prevent hackers and spam by performing data security validation on the form. | | --- | --- |

The HTML form introduced in this section includes the following input fields: required and optional text fields, radio buttons, and a submit button:

View Code »

The form validation rules are as follows:

Field Validation Rules
Name Required. + Must contain only letters and spaces
E-mail Required. + Must be a valid email address (containing '@' and '.')
URL Optional. If present, it must be a valid URL
Comment Optional. Multi-line input field (text area)
Gender Required. Must select one

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


Text Fields

The "Name", "E-mail", and "URL" fields are text input elements, and the "Comment" field is a textarea. The HTML code is as follows:

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

Radio Buttons

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 is as follows:

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

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

| | What is the $_SERVER["PHP_SELF"] variable? <br> <br>$_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script, related to the document root. | | --- | --- |

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

| | What is the htmlspecialchars() method? <br> <br>The htmlspecialchars() function converts some predefined characters to HTML entities. The predefined characters are: & (ampersand) becomes &<br> " (double quote) becomes "<br> ' (single quote) becomes '<br> < (less than) becomes <<br> > (greater than) becomes > | | --- | --- |


What to Pay Attention to in PHP Forms?

The $_SERVER["PHP_SELF"] variable can be exploited by hackers!

When hackers use cross-site scripting (XSS) HTTP links to attack, the $_SERVER["PHP_SELF"] server variable can also be injected with scripts. The reason is that cross-site scripting attaches to the path of the executing file, so the string of $_SERVER["PHP_SELF"] will include the JavaScript code following the HTTP link.

| | XSS is also called <br>CSS (Cross-Site Script). Malicious attackers insert malicious HTML code into web pages. When users browse the page, the embedded HTML code within the web page is executed, achieving the attacker's special purposes. | | --- | --- |

Specify the following form file name as "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 much better.

However, consider that users might enter the following address in the browser address bar:

http://www.tutorialpro.org/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E

In the above URL, it will be parsed and executed as the following code:

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

A script tag has been added to the code, along with an alert command. This JavaScript code will execute when the page loads (causing a popup to appear for the user). This is just a simple example to illustrate how the PHP_SELF variable can be exploited by hackers.

Note that any JavaScript code can be added within the <script> tags! Hackers can use this to redirect the page to another server, where malicious code can be protected in the page files, and can modify global variables or capture user form data.


How to Prevent $_SERVER["PHP_SELF"] Exploitation?

$_SERVER["PHP_SELF"] can be protected from exploitation by using the htmlspecialchars() function.

The form code would look like this:

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

The htmlspecialchars() function converts predefined characters to HTML entities. Now if a user tries to exploit the PHP_SELF variable, the output will be as follows:

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

Attempting this vulnerability fails!


Validating Form Data with PHP

First, we process all submitted data through PHP's htmlspecialchars() function.

When using the htmlspecialchars() function, if a user attempts to submit the following text field:

<script>location.href('http://www.tutorialpro.org')</script>

This code will not execute because it will be saved as HTML escaped code, like this:

&lt;script&gt;location.href('http://www.tutorialpro.org')&lt;/script&gt;

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

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

Next, let's write these filtering functions into a custom function to greatly increase code reusability.

Name the function test_input().

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

Example

<?php
// Define variables and set to empty values
$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 executing the above script, we check if the form has been submitted via $_SERVER["REQUEST_METHOD"]. If REQUEST_METHOD is POST, the form is submitted - the data is validated. If the form is not submitted, validation is skipped and it displays as blank.

In the above example, all input fields are optional, meaning they will display normally even if the user does not enter any data.

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

❮ Func Array Intersect Uassoc Func String Mb_Strlen ❯