Preventing Cross-Site Scripting (XSS) Attack in PHP

In this tutorial, you will learn how to Prevent Cross-Site Scripting (XSS) Attacks on your site using PHP Language. The main purpose of this tutorial is to provide the students and new programmers with a reference for learning the best practices for securing the site that they will develop or currently developing. Here, snippets and a sample source code are also provided to give you a better understanding of the topic of this tutorial.

What is Cross-Site Scripting (XSS) Attack?

Cross-Site Scripting Attacks or also known as XSS Attacks is a web security vulnerability that enables the malicious attacker/hackers to inject or execute scripts on the client side. This kind of security vulnerability for that site allows the user to enter text content such as comment sections, forums, etc.

How to Prevent Cross-Site Scripting (XSS) Attacks in PHP?

To Prevent Cross-Site Scripting (XSS) Attacks in PHP, developers must always escape the text content or string that the user has submitted on the site on any instance before rendering or displaying it. Doing so, the malicious scripts will be served as normal text that can only be displayed and won't execute.

PHP comes with built-in methods or functions that are very useful for preventing Cross-Site Scripting (XSS) Attacks. Here are some of the methods of PHP that can help you to prevent XSS attacks:

  • htmlentities() - a method for converting all applicable characters to HTML Entities.
  • htmlspecialchars() - a method for converting all special characters to HTML Entities.
  • filter_input() - a method for getting the external or global variables such as POST and GET data and filtering it optionally (sanitized).
  • filter_var() - a method for filtering the given variable.

Although, there are a lot more methods that are useful. The list above is some of the effective built-in methods or functions that PHP has to prevent XSS vulnerability. The listed methods enable you to sanitize or escape the text content first before rendering it to the client-side side.


Let's pretend that your site contains the following form.

  1. <div class="card rounded-0 mb-3 shadow">
  2. <div class="card-header rounded-0">
  3. <div class="card-title"><b>Sample Form</b></div>
  4. </div>
  5. <div class="card-body rounded-0">
  6. <div class="container-fluid">
  7. <form id="sample-form" action="" method="POST">
  8. <div class="mb-3">
  9. <label for="dynamicContent" class="form-label fw-light">Content</label>
  10. <textarea class="form-control form-control-sm rounded-0" name="dynamicContent" id="dynamicContent" rows="10" style="resize:none" placeholder="Write your content here..."><?= $_POST['dynamicContent'] ?? "" ?></textarea>
  11. </div>
  12. </form>
  13. </div>
  14. </div>
  15. <div class="card-footer text-center rounded-0">
  16. <button class="btn btn-primary rounded-pill" form="sample-form">Submit Content</button>
  17. </div>
  18. </div>

If the user will enter and submit the following value:

  1. alert("Your site security is vulnerable to XSS Attack!")

The sample text content provided above will result in JS script text content submitted on the form.

Preventing XSS vulnerability in PHP

Then, you render the submitted text content something like the following PHP Script:

  1. <?php echo $_POST['dynamicContent'] ?>

It will run or execute the JavaScript that the user submitted from the form which results to show an alert dialog like the following image.

Preventing XSS vulnerability in PHP

But, if you use the following PHP script for rendering the submitted text content:

  1. <?php
  2. $string = $_POST['dynamicContent'];
  3. $string = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
  4. // Replacing next line into HTML break tag
  5. $string = str_replace(["\n\r", "\n"], "<br/>", $string);
  6. // Replacing tab characters to 5 spaces
  7. $string = preg_replace("/\t/" , "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $string);
  8. // Replacing space character to html non-breaking space
  9. $string = preg_replace("/\s/" , "&nbsp;", $string);
  10. echo $string;
  11. ?>

This will result in the following image:

Preventing XSS vulnerability in PHP

The text content is only shown as normal text content and won't execute the submitted JS script which means that your PHP script rendered textual content that is well escaped or sanitized.


I also provided the complete source code zip file that I created for this tutorial. You can download it on this site for free so you can run and test it on your end. The download button is located below this tutorial's article content.

That's the end of this tutorial. I hope this Preventing Cross-Site Scripting (XSS) Attack in PHP Tutorial will help you with what you are looking for and will give you an idea/knowledge for securing current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment