Sunday, April 22, 2012

Preventing XSS (PHP)

Lets take an example :


<html>

<body>

<form action="xss.php" method="POST">

Val: <input type="text" name="val">
<input type="submit" name="valu" value="submit">
</form>
</body>
</html>

<?php

$val=$_POST['val'];
if ($_POST['valu']=='submit')
{
echo $val;
}
?>


Here u can see that when we try to enter a value it directly echo's back to us..see below:



and when i try to enter the below html code ..it is running the script.


from this we know that it runs .. so lets now try to run a javscript
<script>alert("xss")</script>












Now to prevent this we use html function called "htmlentities".

now the code will be:


<?php

$val=htmlentities($_POST['val'],ENT_QUOTES,'UTF-8');
if ($_POST['valu']=='submit')
{
echo $val;
}
?>

now try to run the script :: it doesnt gets executed.... :)







cheers!..  




5 comments:

There is no difference b/w 1st code and 2nd code
Check it

When i insert script alert("pankaj"

... the page is returning me to as blank ...
i've tried in chrome ,fiefox and IE8

same result appears in all the above mentioned browsers...

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More