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 the 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 in to database, the situation is very critical. Luckily, PHP has some built in functions to validate the data inserted by a user using user input form. Before explaining those functions, it is better 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 strings 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.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. htmlspecialchars() Htmlspecialchars() function will convert any HTML element in the user string to HTML escaped characters and prevent it from executing the code. 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.
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().