September 9, 2012

mysql_real_escape_string() for entire $_REQUEST array, or need to loop through it?

Question by ajo

Is there an easier way of safely extracting submitted variables other than the following?

if(isset($_REQUEST['kkld'])) $kkld=mysql_real_escape_string($_REQUEST['kkld']);
if(isset($_REQUEST['info'])) $info=mysql_real_escape_string($_REQUEST['info']);
if(isset($_REQUEST['freq'])) $freq=mysql_real_escape_string($_REQUEST['freq']);

(And: would you use isset() in this context?)

Answer by deceze

To escape all variables in one go:

$escapedGet = array_map('mysql_real_escape_string', $_GET);

To extract all variables into the current namespace (i.e. $foo = $_GET['foo']):

extract($escapedGet);

Please do not do this last step though. There’s no need to, just leave the values in an array. Extracting variables can lead to name clashes and overwriting of existing variables, which is not only a hassle and a source of bugs but also a security risk. Also, as @BoltClock says, stick to $_GET or $_POST. Also2, as @zerkms points out, there’s no point in mysql_real_escaping variables that are not supposed to be used in a database query, it may even lead to further problems.

Answer by Starx

You can also use a recursive function like this to accomplish that

function sanitate($array) {
   foreach($array as $key=>$value) {
      if(is_array($value)) { sanitate($value); }
      else { $array[$key] = mysql_real_escape_string($value); }
   }
   return $array;
}
sanitate($_POST);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!