Jan 23, 2014, by admin
Cross-Site Scripting (XSS) is a type of security hole where a hacker attempts to inject client-side scripting into a web page that others are able to view. The attack could be as simple as an annoying alert window or as sophisticated as stealing a logged in user’s credentials commonly saved browser cookies. With a user’s credentials, a hacker could gain access to sensitive parts of your website or web application. In this article, I’ll show you a few ways to protect your website from XSS with PHP.
If you allow user input on your site or application (like comments, forums, etc), you could be the target of an XSS attack. The hacker’s goal is to submit a comment, forum post, etc with JavaScript code inside and have it executed on the web page.
This is accepted by your site and displayed into the comments. One of your members visits the comment page while logged in. His browser parses the malicious script and adds the invisible image tag to the page. His browser then requests the URL of the image: http://site.com/PHPSESSID=3D3c2542747972f9a08b8759eafd079d7b
Now attackers’ server logs member’s session cookie. Attacker can now use the same session cookie as Member.
This is a simple XSS attack, but malicious users can also use other ways to attack into your site. You need to focus on your security from a broad perspective and make sure that you have covered absolutely every angle. It only takes one hole to circumvent all your defences.
So stop trusting your users input. Escape all your user inputted data before printing it out to a HTML page. PHP has a couple of different functions you can use to filter user input, namely: htmlentities() and strip_tags().
The htmlentities() function translates all applicable characters to their html entity counterparts. For example, using this function <script> would become <script>. This function is good for escaping data and might prevent some types of attack. When using the htmlentities function, make sure the second argument is set to ENT_QUOTES, like this:
You can also use PHP strip_tags() function to remove any HTML tags, but even this still would not prevent all types of XSS attacks. So what can you do? You can use PHP to search for “script” tag and replace it with scri pt. Cutting up the code like this will prevent it from executing while still displaying the output.
Hopefully this article gave you a good idea of what cross-site scripting attacks are and how you can prevent them from happening to your code. Never trust data coming from the user or from any other third party sources. You can protect yourself by validating the incoming values in a well defined context, sanitizing the data to protect your code, and escaping output to protect your users. After you’ve written your code, be sure your efforts work correctly by testing the code as thoroughly as you can.