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!..  




Twitter Delicious Facebook Digg Stumbleupon Favorites More