Prevent Malicious User Inputs In PHP Form

Published by: Alex George on October 19, 2015
A professional website always must have a way to receive user inputs either in the form of a comment column or in the form of a user input form. It is a must for successful websites to receive feedback from their users but some malicious persons use this option to inject malicious scripts to the website. If the data entered by the user is directly inserted into the database, the situation is very critical. Luckily, PHP has some built-in functions to validate the data inserted by a user using the user input form. Before explaining those functions, it is better to understand the effects of tricky external credentials.

Effects of Malicious User Inputs on a Website


Though a PHP address form is intended to receive user details like name, address etc, it will take every string submitted unless we don't implement strict validation. If someone enters a script instead of name, it is possible that the form will accept it unless there is a validation. It will be extremely dangerous if we use the same input for any data base query.


Built in PHP Functions To Validate User Inputs Though Form


Here is the list of three important functions which validates data entered through a PHP form.

  1. Trim() :

    Trim() function is used to remove any extra space, new line etc from the form inputs. Every text filed values must be passed through trim() function before taking the input for operations.

  2. htmlspecialchars()

    Htmlspecialchars() function will convert any HTML element in the user string to HTML escaped characters and prevent it from executing the code.

  3. stripslashes()

    This function removes backslashes (\) from the user input data.


By the combined use of these three functions, we can reduce the risk of taking user input through PHP form. Now let us check how to implement these three functions in our code.


Implementation of PHP Form Validation In a Code


Let us consider the username received through a PHP form is $_POST["username"];. We need to pass the value to a variable like $user=$_POST["username"]; Right now we do not know whether the input is harmless. So we need to create a custom function by using the three functions explained before.

function validate($x)
{
   $x= trim($x);
    $x= stripslashes($x);
    $x= htmlspecialchars($x);
    return $x;

}


Now the user inputs must be sanitized using the custom function we have created. For example, we are going to validate the $user using the function validate().

validate($user);


Related Articles
  1. Multiple Article Submission Penalty

  2. Web Traffic Vs AdSense Earnings

  3. Optimize Blogger Template

  4. How to Calculate CPC

No comments:

Post a Comment

Newer Post Older Post Home