开发者

How to loop on $_GET array and escape all its variables?

How to mysql real escape str开发者_开发问答ing all $_GET contents?

Thanks


You shouldn't do this.

Instead, use PDO and prepared queries to insert, manipulate and query your data, which gets around the need to escape things. This frees you from worrying about if you've escaped things properly (or perhaps you forgot altogether somewhere, oops!)


<?php
array_walk($_GET, 'mysql_real_escape_string');
?>

you may for example use the same technique to trim() its content

array_walk for more details


The $_GET superglobal is an array so you can iterate over it like any other.. but for security purposes, you really shouldn't. Each parameter of the array should likely be filtered/sanitized/escaped in a different way with a different context.

For example, if you were processing a blog post, you'd likely have a title, body, publish on date, and author:

  • The title probably shouldn't have any html tags.
  • The body may allow some tags, but a very limited set.
  • The date is likely an integer (timestamp) or a specific date format or a series of numbers from dropdowns.
  • The author may be a string (username) or preferably an author_id. If it's an id, it should be an int and doesn't need escaping.

If you filter them all the same, you're missing the context and purpose of each of those.


Something like this:

foreach ($_GET as $key => $val)
{
   $_GET[$key] = mysql_real_escape_string($val);
}

But i agree with Pekka, that's not a good idea.


It is better to use parameterized quires, but if an application has already been written its expensive to go back and rewrite every query. This is a cost effective patch and it will work in most cases, just make sure to test your code with Wapiti(open source) or Acunetix ($) or NTOSpider($$$).

Keep in mind you can pass arrays via GET. ?var[1]=test;.

function escape_deep($value) 
{ 
    $value = is_array($value) ? 
                array_map('escape_deep', $value) : 
                mysql_real_escape_string($value); 

    return $value; 
} 
function stripslashes_deep($value) 
{ 
    $value = is_array($value) ? 
                array_map('stripslashes_deep', $value) : 
                stripslashes($value); 

    return $value; 
} 
if(!get_magic_quotes_gpc()){
   $_GET=escape_deep($_GET);
}else{
   $_GET=stripslashes_deep($_GET);
   $_GET=escape_deep($_GET);
}

If magic_quotes_gpc is on, then you don't want to add slashes twice. Also keep in mind that magic_quotes and this method of escaping doesn't stop everything. For instance this query is still vulnerable:

mysql_query("select name from usesr where id=".$_GET[id]);

exploit:

http://localhost/vuln.php?id=1 and sleep(500)

patch:

mysql_query("select name from usesr where id='$_GET[id]'");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜