Preventing XSS Attacks

XSS Attacks

In my last post I explained you what an XSS attack mean in this post I will explain how can we prevent such attacks.

Preventing a webpage from an XSS attack should always be there in your mind.You can better create a function that prevents these attacks and call it everytime.Fortunately its very simple to prevent these attacks.You should never trust a user that he or she will always input proper data.There are millions of attackers sitting online just to find a prey.

Every bit of data must be validated on input and escaped on output. This is the golden rule of preventing XSS.

To prevent attacks we should follow data validation,data sanitization and output escaping.

Data Validation

It is a process where you validate data according to its requirement.Every piece of data must be validated.

Eg : When you want to validate a phone number you should only allow the user to enter numbers and discard strings or characters.And if you want to allow some special characters like “plus”,”brackets” or “dashes” as such characters are also an acceptable phone format you may use a regular expression for same.

// validates an Indian mobile number
if (preg_match('^((\\+91-?)|0)?[0-9]{10}$', $phone)) {
    echo $phone . " is valid format.";

Data Sanitization

Its a process where you clean up the data by removing any unwanted bits.

Eg : You may want to remove all HTML markups from the data.

// sanitize HTML from the comment
$comment = strip_tags($_POST["comment"]);

Output Escaping

When presenting the data as output via a browser the output should be escaped to protect its meaning.

// escape output sent to the browser
echo "You searched for: " . htmlspecialchars($_GET["query"]);


Never trust the data coming from users and take all required actions to prevent such attacks.You can prevent them with Data Validation and Sanitization and also by escaping Output to protect users.





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s