XSS – PHP Secure Coding

Case #1

HTML escape before inserting untrusted data into HTML element content.

<?php
  $str=$_POST["data"];
  $str_safe=htmlspecialchars($str, ENT_QUOTES);
?>
<h1><?php echo $str_safe; ?></h1>

Case #2

JavaScript escape before inserting untrusted data into JavaScript data values.

<?php
  $str=$_POST["data"];
  $safe=strip_tags($str);
?>
<script>alert("<?php echo $safe; ?>");</script>

 

References
http://php.net/manual/en/function.htmlspecialchars.php
http://php.net/manual/en/function.htmlentities.php
http://in3.php.net/strip_tags