Jump to content

Cleaning user input and queries automatically


bachx

Recommended Posts

I've searched for a function to allow me to filter all user input ($_POST/$_GET) without having to do it manually for every field. I've discovered this one:

 

$_POST = array_map('cleanData', $_POST);
$_GET= array_map('cleanData', $_GET);

function cleanData($data) {
     $data = trim($data);
     $data = htmlentities($data);
     $data = mysql_real_escape_string($data);
     return $data;
}

 

Is the above code fully secure? Can I safely use $_POST/$_GET in queries directly? Or are there better alternatives out there?

 

Thanks.

 

Can I safely use $_POST/$_GET in queries directly?

 

Definetly not!!

 

There probably are functions to clean input but security should be application specific.

 

You are on the right lines here but you do have to do it all manually.

 

Best practice is to get the user input then clean it appropiatley and store it within a $clean array;

 

$clean = array();

if (ctype_alpha($_POST['username']))
{
     $clean['username'] = $_POST['username'];
}
if (ctype_alnum($_POST['password']))
{
     $clean['password'] = $_POST['password'];
}

 

 

Obviously your checks would be more intensive.

For string type data, use mysql_real_escape_string() for numeric data, cast it as the correct type. i.e. if an integer is expected, $new_value = (int) $_POST['int']; etc. Also, validate that the values are in line with what they should be using other types of field validation, like checking for empty fields, unwanted characters in fields and so on.

Thanks for the replies but I need a definite answer.

 

Is it wrong to use my code in the OT to clean all user input automatically? It will handle both strings and integers just fine. My actual code is something like this:

 

$value_arr = array_map('cleanData', $_POST);

 

so, for example, is $value_arr['username'] safe to insert into a query directly, assuming I passed all $_POST data to the cleanData function?

Thanks for the replies but I need a definite answer.

 

Is it wrong to use my code in the OT to clean all user input automatically? It will handle both strings and integers just fine. My actual code is something like this:

 

$value_arr = array_map('cleanData', $_POST);

 

so, for example, is $value_arr['username'] safe to insert into a query directly, assuming I passed all $_POST data to the cleanData function?

 

Anyone?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.