HS Banner
Back
PHP Form Validation

Author: Admin 01/28/2024
Language: PHP
Tags: php security forms


Description:

Think SECURITY when processing PHP forms! This shows how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!

Article:

PHP Form Validation

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>

Think SECURITY when processing PHP forms!

This shows how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!

Validate Form Data With PHP

The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.

When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:

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

- this would not be executed, because it would be saved as HTML escaped code, like this:

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

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

  1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
  2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).

We will name the function test_input().

Now, we can check each $_POST variable with the test_input() function, and the script looks like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = check_input($_POST["name"]);
  $email = check_input($_POST["email"]);
  $website = check_input($_POST["website"]);
  $comment = check_input($_POST["comment"]);
  $gender = check_input($_POST["gender"]);
}

function check_input($data): string
{
    $data = trim($data);
    $data = strip_tags($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

This maybe a bit overkill but better to be safe.


Back
Comments
Add Comment
There are no comments yet.