Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize query string in PHP

Tags:

php

I have a webpage with a query string.

In PHP I have:

$querystring=$_SERVER["QUERY_STRING"];
echo "<html><head></head><body>
<a href='index.php?$querystring'>test</a>
</body></html>";

Do I need to sanitize the querystring?
If yes, how do I sanitize and what are some possible attacks if I don't?

like image 677
David19801 Avatar asked Dec 02 '11 20:12

David19801


1 Answers

If you're running PHP >= 5.2.0, use filter_input or filter_input_array.

Let's say your URL and query string is something like http://example.com/?liquor=gin&mixer=tonic&garnish=lime.

To filter, you would do something like the following.

/*
 FILTER_SANITIZE_STRING removes most dangerous characters. That may 
 not always be what you want. Read the PHP filters docs. 

 We are also overwriting the $_GET array (the query string) with the sanitized
 versions of these variables.
*/

$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);

/* 
rebuild query string using white listed variables, 
not $_GET to prevent variable injection as Mārtiņš Briedis 
suggests above.
*/

$qv['liquor']  = $_GET['liquor'];
$qv['mixer']   = $_GET['mixer'];
$qv['garnish'] = $_GET['garnish'];

# build and URL encode the query string using the above array.
$querystring = http_build_query( $qv );
like image 52
webinista Avatar answered Oct 18 '22 02:10

webinista