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 https://example.com/sale?category=Gifts%27+OR+1=1–
// Let's try without sanitizing print_r($_GET); // Result // Array ( [category] => Gifts' OR 1=1-- )
Now, let’s try sanitizing
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_ENCODED); print_r($_GET); // 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
and here is after sanitizing
For more PHP code examples – check out the PHP category