PHP: Preventing typical XSS attacks

XSS attacks plague beginner programmers and are a significant vulnerability for commercial web hosts & website operators.  XSS means “cross-site scripting“.  These exploits work on the client side. Often, hackers put some type of JavaScript in content that users submit that allow them to steal the data from a cookie.  XSS attacks are pretty difficult to prevent.  Hackers have been successful with XSS attacks on most, if not all, of the biggest sites on the net.

To help prevent XSS attacks, it’s best to restrict and filter the data that you get from a user through your site.  Have you ever wondered why popular bulletin boards, such as vB or phpBB, use custom tag formats like [url] or [b]?  They’re trying to prevent attacks.

This tutorial is a very basic example of a way to help prevent XSS attacks.  There are other methods — and more comprehensive methods out there.

okHTML function:
Let’s start with a simple function that converts any HTML code (or character) into literals.

Select Code
function ok_HTML($string, $length = null)
// get rid of the extra space
$string = trim($string);

// avoid unicode codec issues
$string = utf8_decode($string);

// convert HTML characters
$string = htmlentities($string, ENT_NOQUOTES);
$string = str_replace("#", "#", $string);
$string = str_replace("%", "%", $string);

$length = intval($length);
if($length > 0) {
$string = substr($string, 0, $length);
return $string;

The Explanation:
One  of the  most important components of that function is the htmlentities() funcion call that converts &, <, and > into &amp;, &lt;, and &gt;. This helps resolve the simple hacks.  We’re not done yet, though.  All XSS attacks aren’t basic.  Hackers know programmers have implemented these attacks to they tend to encode their hacks and malicious scripts in UTF-8 or hexadecimal instead of using the normal ASCII text.

To help prevent this, transform_HTML() takes the additional step of converting # and % signs into the correct entities.

In my readings on preventing XSS attacks, many experts recommend that you limit the  string length in case some goober tries to overload your string with a very, very long input in hopes that they’ll crash the server or your database. You can edit the $length parameter to help control this.

That’s it for today,

Disclaimer: As always, I want to add my handy-dandy disclaimer.  Please understand that this tutorial is intended to demonstrate a specific function.  Please review the code and add appropriate security measures before using it in a production environment.

Leave a Reply

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