PHP Form Validation

In this lesson, you will learn how to validate Forms in PHP, best practices, and examples to understand the topic better.


What is PHP Form Validation?

While processing PHP forms, consider SECURITY! Validating your Form’s input is crucial for protecting it from spammers and hackers. This tutorial will teach you how to process PHP forms securely. The HTML form in this tutorial includes a submit button, radio buttons, and mandatory and optional text fields:

Field Name Validation Rules
Name + Must be limited to letters and whitespace.
E-mail + Must include a working email address (with @ and.)
Website Optional. If present, it must have a legitimate URL.
Comment Optional. multiple-line text input (textarea)

Validate HTML Form Controls using HTMLspecialchars() method

Examining the Form’s simple HTML code is the first step. The comment box is a textbox, whereas the name, email address, and website fields are text input elements, and the gender options are radio buttons. The Form Data with multiple lines is transmitted using the method=”post” when submitted. The htmlspecialchars() method converts special characters into HTML entities. $_SERVER["PHP SELF"] is a superglobal variable that returns the script’s name. Instead of navigating to a new page, the $_SERVER["PHP SELF"] sends Form Data to the current page. Error notifications will appear on the same page as the Form.

Simple HTML Form:
<form method="post" action="<?php echo HTMLspecialchars($_SERVER["PHP_SELF"]);?>">
  First Name: 
  <input type="text" name="f_name">
  Last Name: 
  <input type="text" name="l_name">
  Phone No: 
  <input type="text" name="phoneno">
  Address: 
  <textarea name="address" rows="5" cols="30">
  </textarea>
  Select Gender:
  Female: 
  <input type="radio" name="gender" value="fe_male">
  Male: 
  <input type="radio" name="gender" value="male">
  Click Here:
  <input type="submit" name="submit" value="submit">
</form>

Cross-Site Scripting

Cross-Site a particular kind of computer security flaw called cross-site scripting (XSS) is frequently discovered in Web applications. XSS allows attackers to insert client-side scripts into web pages that other users are seeing. A user can insert a slash /, and then specific Cross-Site Scripting (XSS) commands to execute if PHP SELF is used on your page.

Hackers may use the $_SERVER["PHP SELF"] property! Special characters are converted to HTML entities using the HTMLspecialchars() method. As a result, it will use and instead of other HTML characters. This will stop attackers from using HTML or Javascript code (Cross-site Scripting attacks) to abuse the code in forms.

Let’s think the myform.php page contains the following form:

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

If a user enters the URL “https://www.mysite.com/myform.php” in the address bar, the above code will look like

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

But suppose a user types the following URL into the address bar:

https://www.mysite.com/myform.php/%589E%3Cscript%3Ealert('hacked')%78C/script%48E

The code shown above will be rendered as:

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

It is a very safe case of how the PHP_SELF variable is exploited. This code includes a script tag and a caution command. And when the page loads, the JavaScript code executes (the client will see an alert box).

Note
Be conscious that any JavaScript code can be included in the script tag. A hacker can divert the client to a record on another server, holding harmful code that can change the data and send it to another address.

So, it is important to validate web form data to avoid hacking. To avoid $_SERVER["PHP_SELF"] exploits use the HTMLspecialchars() function.

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

Now, suppose the user attempts to exploit the PHP_SELF variable. The following outcome will occur in that case, and the exploit fails without generating any damage.

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

PHP form with validation

<?php
$f_name = "";
$l_name = "";
$gender = "";
$address = "";
$f_name_error = "";
$l_name_error = "";
$gender_error = "";
$address_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["f_name"])) {
        $f_name_error = "First Name is required";
    } else {
        $f_name = validate_data($_POST["f_name"]);
    }
    if (empty($_POST["l_name"])) {
        $l_name_error = "Last Name is required";
    } else {
        $l_name = validate_data($_POST["l_name"]);
    }
    if (empty($_POST["address"])) {
        $address_error = "";
    } else {
        $address = validate_data($_POST["address"]);
    }
    if (empty($_POST["gender"])) {
        $gender_error = "Gender is required";
    } else {
        $gender = validate_data($_POST["gender"]);
    }
}
?>

As you have noticed, we use $_SERVER["REQUEST METHOD"] to determine whether the Form has been submitted at the beginning of the script. Then, the form is sent if the REQUEST METHOD is POST and needs validation. Skip the validation and show a blank form if it hasn’t been submitted. Nevertheless, all of the input fields in the example above are optional. The script still functions appropriately even if the user doesn’t enter any data.

  • All variables will initially be passed through PHP’s HTMLspecialchars() method.
  • Using the PHP trim() function, remove unnecessary characters (extra space, tab, newline) from user input data.
  • Remove backslashes() from user-supplied data (using the PHP function stripslashes()).

PHP Complete Form with Required fields

There is no assurance that user-provided information is always accurate. PHP validates the data submitted by an HTML form on the server. It would be best if you verify the following:

  • Empty String
  • Validate String
  • Validate Numbers
  • Validate Email
  • Validate URL
  • Input length

For example, you have created an HTML form, and a few checks are required before submitting data to the server. In the below example, we created a form with HTML control like “First Name,” Address”, “Last Name”, and “Gender.” All fields are required; these HTML form fields cannot be left blank and must be filled out.

Field Names and Validation
First Name and Last Name Required. + Only letters and whitespace allowed
Address Optional. Multi-line input field (textarea)
Gender Required. must choose one

PHP Complete form with validation

<!DOCTYPE HTML>

<HTML>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
$f_name = "";
$l_name = "";
$gender = "";
$address = "";
$f_name_error = "";
$l_name_error = "";
$gender_error = "";
$address_error = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["f_name"])) {
        $f_name_error = "First Name is required";
    } else {
        $f_name = validate_data($_POST["f_name"]);
    }

    if (empty($_POST["l_name"])) {
        $l_name_error = "Last Name is required";
    } else {
        $l_name = validate_data($_POST["l_name"]);
    }

    if (empty($_POST["address"])) {
        $address_error = "";
    } else {
        $address = validate_data($_POST["address"]);
    }
    if (empty($_POST["gender"])) {
        $gender_error = "Gender is required";
    } else {
        $gender = validate_data($_POST["gender"]);
    }
}
?>
<form method="post" action="<?php echo HTMLspecialchars(
    $_SERVER["PHP_SELF"]
); ?>">
First Name: <input type="text" name="f_name">
<span class="error">* <?php echo $f_name_error; ?></span>
Last Name: <input type="text" name="l_name">
<span class="error">* <?php echo $l_name_error; ?></span>
Address: <textarea name="address" rows="5" cols="30"></textarea>
<span class="error">* <?php echo $address_error; ?></span>
Select Gender:
Female: <input type="radio" name="gender" value="fe_male">
Male: <input type="radio" name="gender" value="male">
<span class="error">* <?php echo $gender_error; ?></span>
Click Here:<input type="submit" name="submit" value="submit">
</form>
<?php
echo "<h2>-----RESULT---</h2>";
echo $f_name;
echo "<br>";
echo $l_name;
echo "<br>";
echo $address;
echo "<br>";
echo $gender;
?>

</body>
</HTML>

We add a small script after each required field in the HTML form, which generates the appropriate error message if necessary (if the user submits the form without filling out the required fields).

This concludes the PHP Form Validation lesson. In the next lesson, you will learn about PHP include & require.