Last updated on February 1st, 2022 at 05:19 pm

Cross site scripting can be dangerous especially when hackers try to exploit a website in PHP that doesn’t validate query strings once passed.

In this tutorial I am going to define how to prevent cross site scripting in PHP while using query strings.

Let’s define a simple function to prevent the query sting from being tampered with external code.

Lets take an example, If you have a webpage like

http://www.mistonline.in/search/index.php?name=java , there is every possibility that a hacker can try to inject some javascript in that something like this

http://www.mistonline.in/search/index.php?name=<script language=javascript>setInterval
("window.open('http://www.baddomain.com/','innerName')",50);
</script>

Like this there are numerous techniques, So in order to prevent this from happening on your webpage use the below code which is very simple written using php


A Quick Look at Cross Site Scripting – Coding for our safety

<?php
function validateQueryString ( $queryString , $min=1,
$max=32 ) {
if ( !preg_match ( "/^([a-zA-Z0-9]{".$min.",".$max."}=[a-zA-Z0-9]{".$min.",".$max."}&?)+$/", $queryString ) ) {
return false;
}
return true;
}?>

Once we have defined the above function, we call it this way:

<?php
$queryString = $_SERVER['QUERY_STRING'];
if ( !validateQueryString ( $queryString ) ) {
#header('Location:404.php' );
echo "Page Not Found";
}
else {
echo "Welcome to ".stripslashes($_GET['name']." pages");
}?>

As you can see we can either redirect the page to a 404.php or just print “Page Not Found” when there is a script being passed to query string instead of genuine key / value pair.

Demo With Bad Query String

Demo With Good Query String

Leave a Reply

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