Best Practices to Prevent XSS in PHP Web Apps

Best Practices to Prevent XSS in PHP Web Apps

Cross-Site Scripting is a type of security vulnerability that normally occurred in web applications and is often abbreviated as XSS. In case you’re wondering, we don’t use the abbreviation CSS because we already use that for Cascading Styles Sheets when we’re designing our web pages.

XSS was originally called cross-site because of web browser security flaws. Using XSS, you can transfer information/data from one site to another if you had both sites’ windows open in your browser. 

In this article, I will walk you through the details about the XSS and how you can prevent PHP XSS attacks on your web app.

XSS usually gets inserted through a webpage using a web form or hyperlink. This code can be used via any client-side languages such as JavaScript, PHP, HTML, VBScript. 

Nowadays, given the rampantness of past XSS vulnerabilities, browsers take security into account and don’t generally allow information to jump from one browser screen to another. It is also important to have complete awareness and knowledge about XSS attack examples in your PHP applications to be able to set up prevention measures in time. 

Practices to Prevent XSS in PHP Web Apps


Types of XSS Vulnerabilities

There are 3 main types of XSS attacks.

  1. Stored XSS 
  2. Reflected XSS
  3. Dom Based XSS (Document Object Model)

Stored XSS

Stored Cross-Site Scripting [XSS] is a very dangerous form of Cross-Site Scripting. Web applications that allow users to store data in the database are potentially exposed to this type of attack.

Stored XSS happens when an XSS attacker injects malicious code into a website with the code being saved to a database. Later on, when a web user accesses the page, he may unknowingly retrieve that file and thus the script will run in the user’s browser.

Whenever a client sends an HTTP request to the server and the server sends an HTTP to respond with malicious code because malicious code saves in the database, it will harm the client. The severity of this kind of attack is very high.

Reflected XSS

This is a type of Cross-Site Scripting in which an attacker injects some JavaScript code using any form field on a website. Whatever script will add to the browser will never affect any other user or any other users will be harmed.

Take an example of any search engine (Google, Bing). You’re able to input a query and search for any information, but what would happen if you can add scripts in the input field, and the script would perform any function? Maybe it took the user’s credentials, it took cookies information. If you have similar cookies as for any other user, you can access all their data in your browser because you ran a search into a malicious search box.


DOM stands for Document Object Model. In this type of attack, an attacker injects JavaScript code into the HTML DOM through any input field. 

DOM XSS is not much different than Stored and Reflected XSS, where scripts can be injected and in the background, the payload gets executed and makes further changes to the DOM enrollment. This is done on the Client-Side, so it does not look for the server response and thus a DOM XSS is executed easily. 

This can occur when a malicious script is passed into a URL and the client-side scripts read it to modify the DOM.

So now the question is how do we differentiate between a normal XSS and a DOM XSS? The only difference is the payload that won’t be reflected in the source code of the web application.

The Reasons Behind XSS

XSS is often easy to execute and create because of errors in the development of that website application. This makes it easy for attackers to take advantage of because it is relatively easy once an attacker learns of the weakness in the app to simply paste some JavaScript or other code into an input textarea. After all, why not? It runs code. It runs bad code. It’s not anyone’s fault but the web developer’s that code was even allowed to be submitted in the first place. 

You should consider data validation or restrictions while creating web pages with input fields.

Possible Loss Due to XSS

XSS allows attackers to insert a series of malicious scripts into websites, which they can then use to steal user’s cookies or even access their login credentials, credit card details, or any useful information.

The risk created by Cross-Site Scripting is higher than you’d expect since it doesn’t just allow the attacker of user data and information, something that many other vulnerabilities set out to achieve in this attack: with XSS there is an added feature: the attacker commits these crimes on websites that, in the user’s eyes, should be fully trustworthy, so they don’t worry about this kind of theft happening and don’t necessarily think about keeping their blinders on.

How to Prevent PHP XSS attacks

There are several things you can do for XSS Protection on PHP Applications. One of the best things you can do is make sure you know what you are clicking on. Do not click on unknown links in your inbox, and do not click on the links you receive in your text messages or social account inboxes. 

Always know where that link takes you (check the path from the URL). You may want to consider disabling scripts from the input field or make sure you verify the input before hitting Submit. The end-user should not be able to save scripts or install scripts in your app. If you can stop code from being executed, then you know that a site script attack won’t work.

Make sure you keep your web browsers and other web-based applications updated on your system. As many older browsers have vulnerabilities that allow sites to access XSS scripts, you must update your browser to ensure you’re ahead of the newest possible bugs and vulnerabilities.

Preventing XSS in PHP

The following are some ways in which we can prevent XSS in our web applications –

  • htmlspecialchars — Convert special characters to HTML entities. This is one of the famous methods to prevent XSS:
    • < (less than) &amp;lt;
    • (greater than) &amp;gt;
    • & (ampersand) &amp;
  • Strip_tags — Strip HTML and PHP tags from a string. This function tries to return a string with all NULL bytes, HTML, and PHP tags stripped from a given string.
  • Style-src — Limits the sources for CSS files.
  • Connect-src — Directive restricts the URLs which can be loaded using script interfaces. This helps guard against cross-site scripting attacks (XSS) on PHP Applications,

Third-Party PHP Libraries

There are also third-party PHP libraries that help in the prevention of XSS. Some of these are listed below:

  • PHP Anti-XSS
  • HTML Purifier
  • htmLawed

Among all of these, PHP Purifier is frequently maintained and updated. It is quite simple to use once the developer has a basic level of PHP knowledge.


Cross-Site Scripting is a versatile attack. It could be used to steal very sensitive information such as user credentials, cookies, and commercially valuable data. 

We should try not to insert user-controlled data unless it’s explicitly needed for the application to function. Comments can be its best example where a user can enter malicious XSS causing scripts. 

Before the deployment of PHP web application, try to create some test cases and perform some penetration tests on your web application to find and fix PHP security vulnerabilities that an attacker could exploit in your app.

Let me know in the comments section below if you need me to add any other PHP XSS prevention tips.

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Best Practices to Prevent XSS in PHP Web Apps 1

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]


Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

Keep reading the article at The Official Cloudways Blog. The article was originally written by Shahzeb Ahmed on 2021-01-26 09:57:10.

The article was hand-picked and curated for you by the Editorial Team of WP Archives.

Disclosure: Some of the links in this post are "affiliate links." This means if you click on the link and purchase the product, We may receive an affiliate commission.

Leave a Comment

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

Show Your ❤️ Love! Like Us
Scroll to Top