Stopping XSS Attacks

Cross-site scripting attacks are a valid concern when creating a dynamic PHP application. If security measures are not taken, users could throw off the layout of a forum or other page when they submit info via a form, especially if they inject HTML or other code into an unsecured form. Imagine if someone added a comment or reply to a forum post that had inline styles in it and your whole page was ruined by it. Worse yet, imagine someone including a script in a submitted form that took down your entire site or stole user's data or info. The second example screams lawsuit.

Fortunately, there are methods and built-in functions in PHP that can reduce security risks of this sort. Since malicious hackers are always finding workarounds, you are never 100% secure, but you can at least fortify your site. I looked for articles and found a source that i have trusted for help with coding issues time and again - Stack Overflow. They are more of a forum-style site, but they usually provide useful info. I also consulted PHP Master as a source for a more traditional "article" for this discussion. I also got some info from our text book, PHP and MySQL for Dynamic Sites.

Here are the links to my Web resources:

Since it could take 20 or more pages to cover every single tactic to deal with XSS attacks, I will keep this in the scope of a discussion and go over the basics outlined in the PHP Master article. The other two resources are more for reference in case anyone needs them.

According to PHP Master, XSS attacks are one of the top 5 security attacks carried out on a daily basis across the Web, XSS attacks happen via form data input and/or altered URLs. Incorrect data or code is inserted into a page and passes weak validation, leading to problems ranging from layout issues to programming issues.

The example on the PHP Master website is this:

1 <form action="post.php" method="post">
2  <input type="text" name="comment" value="">
3  <input type="submit" name="submit" value="Submit">
4 </form>


Here we have a simple form in which there is a text box for data input and a submit button. Once the form is submitted, it will submit the data to post.php for processing. Let’s say all post.php does is output the data like so:

1 <?php
2 echo $_POST["comment"];

Without any filtering, a hacker could submit the following through the form which will generates a popup in the browser with the message “hacked”.


It was simple, in the example, to inject a script into the form because there was no security validation. Both persistent and non-persistent XSS attcks are viable threats to your site. Non-persistent XSS attacks are only passed through the server, while persistent XSS attacks are stored on the server. Both can cause headaches on a website.

To prevent XSS attacks, PHP Master first says to "never trust data coming from the user or any third party sources" as a first line of defense, prior to writing any code. Always keep this in mind. Data validation, data sanitization, and output escaping are two more specific tactics to prevent XSS attacks.

Data Validation

You can use this code to validate a phone number:

// validate a US phone number

if (preg_match('/^((1-)?\d{3}-)\d{3}-\d{4}$/', $phone)) {

echo $phone . " is valid format.";


Data Sanitization and Output Escaping

Both data sanitization and output escaping manipulate data for safe input to the server and output to the browser, respectively.

Using the textbook's advice, these three functions also help to strip output or change it to HTML entity format:

htmlspecialchars() - turns &, <, >, ', ", into html entitiy format, example: & becomes &amp;, which turns off their functionality to some extent

htmlentities() - turns all applicable characters into html entitiy format, example: & becomes &amp;, which turns off their functionality to some extent like the above function

strip_tags() - removes all HTML and PHP tags

The PHP Master article uses the following code sample to illustrate all three of these secuirty measures working together:

01 <?php
02 // validate comment
03 $comment = trim($_POST["comment"]);
04 if (empty($comment)) {
05     exit("must provide a comment");
06 }
08 // sanitize comment
09 $comment strip_tags($comment);
11 // comment is now safe for storage
12 file_put_contents("comments.txt"$comment, FILE_APPEND);
14 // escape comments before display
15 $comments file_get_contents("comments.txt");
16 echo htmlspecialchars($comments);


Sticking mostly to the PHP Master article, I walked you through some very basic strategies for securing a PHP web application. Better than any code samples or specific tactics is to keep in mind a sense of suspicion for form input, user input, and data coming from any third party source or entity. By being vigilant and keeping security in mind, along with knowing your sites gateways, you can both design and update a site to stop attacks from becoming a daily occurrence.

Contact us

Using the contact form to send us email at below

Keep in touch with us

You can use the following information to contact us if you wanna join us or anything need to communicate.

Name: Brand & Butter Administrator