Sanitize GET request in PHP

Here is how you can sanitize the entire GET array in PHP using filter_input_array with FILTER_SANITIZE_ENCODED.

   // Sanitize the GET request to encode any html elements
   $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_ENCODED);

In this example if someome was to pass a malicious +OR+1=1– as a query string–

// Let's try without sanitizing
// Result
// Array ( [category] => Gifts' OR 1=1-- )

Now, let’s try sanitizing


// Result
// Array ( [category] => Gifts%27%20OR%201%3D1-- )

The effect is the same as putting htmlspecialchars() but in this method is useful if you have a large number of data to sanitize in your GET request, you can do it all at once.

This helps preventing XSS.

Here is an example without sanitizing

XSS without sanitize
Successful XSS without sanitizing

and here is after sanitizing

No XSS after sanitize
No XSS after sanitizing

For more PHP code examples – check out the PHP category

Leave a comment

Your email address will not be published. Required fields are marked *