Yesterday, I saw one of my friend was working on the the contact form and was filtering the user input data(posted variables) individually. He was using a function in PHP to filter the input and using tedious approach while calling the filtering function for each variables with coding each of them in single line . Today, I’m going to show you how can you filter the posted variables easily using callback function in PHP.
PHP function to filter the user supplied data.
function filter_data($val)
{
return htmlentities($val,ENT_QUOTES);
}
This is just a example of very simple function is PHP to filter the user ssubmitted data.But ,you can add more code according to your requirement to make this function robust.
Common programmer’s approach to filter submitted data in PHP
$name=filter_data($_POST['name']); $email=filter_data($_POST['email']); $website=filter_data($_POST['website']);
It was the approach which I’ve used in beginning of my career and most of the beginner PHP programmer use this approach to filter the posted variables.And, the above list can be long if there are more posted data.At that time, it will be very irritating to use the same kind of line in many places.
Using array_map() function to filter the posted data in PHP
As you know, POST variables are super global array in PHP and you can use array_map() function in PHP to filter the input using the callback function. Let’s see how you can filter the the posted data easily,
$post=array_map("filter_data",$_POST);
As you can, each values of POST variables is mapped into another array using a call back function filter_data() which is defined above.
Now, you can access the filtered variables easilly with $post['name'] or $post['email'] etc.
Posted in
Tags: