Sanitize query string in PHP
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 white list any parameters, because a smart attacker could forge a query and attempt a CSRF attack.
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 );