Sanitize query string in 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 a request?
If so, how do I disinfect any possible attacks, if I do not?

+8
php
source share
4 answers

You should use htmlspecialchars($query, ENT_QUOTES) to prevent any XSS attacks.

 echo "<html><head></head><body> <a href='index.php?".htmlspecialchars($querystring, ENT_QUOTES)."'>test</a> </body></html>" 

But still, you should list any parameters in white, because a smart attacker can fake a request and try to attack CSRF .

+6
source share

If you are using PHP> = 5.2.0, use filter_input or filter_input_array .

Say your url and query string are similar to 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 ); 
+12
source share

In this case, you should use the urlencode function.

htmlspecialchars / htmlentities are more suitable when you are going to display the value of the request parameter in the link header, for example, but not in the href / src attributes.

0
source share

You can sanitize a request in several ways, but this is not the place for this. Even if you send a secure request using GET, someone can change the request in the address bar or use tamper data. You should sanitize on index.php (or wherever you process the data). If you are using MySQL, you must misinform this method:

 $field = mysql_real_scape($_GET['field']); 
-3
source share

All Articles