What is (PHP) XSS?

Cross Site Scripting or XSS is the injection of code, typically Javascript (but can be HTML or CSS), into a PHP application from an outside source. XSS is not unique to PHP and can affect any web application which accepts input from outside or untrusted sources. Typical sources of PHP XSS are:

  • Message Boards
  • Private Messages
  • User Comments
  • User Profiles
  • Web Services
The source of XSS attacks is any input our application accepts which is later (or immediately) viewed by other web users.

The consequence of XSS attacks can range from simple defacement to complete account compromise.

PHP Cross Site Scripting Example

Our PHP example XSS attack is in an application that accepts comments. We retrieve the username and comment from the $_POST super global and assign them to variables for later use.

We store the username and comment in our database and later retrieve the comments when any other user requests our page containing comments.

What's important to note in the above code is that user generated comments are displayed to other users.

What would happen if a malicious user submitted a comment that contained script code like the below?

Every time any user views a page containing that particular comment, an annoying alert would be displayed. But what would happen if the attacker submitted much more malicious code, like the below:

With the above code, the attacker steals the unsuspecting user's cookie by sending it to grab.php.

The attacker can later use the stolen cookie to bypass user authentication and impersonate the unsuspecting user.

How do we prevent XSS in PHP?

Looking at the above PHP XSS example, we can break down the vulnerability into 3 parts:

  • Input Filtering
  • Input Validation
  • Output Escaping

Our code above did not filter the input $_POST['comment'] before assigning it to a variable. To prevent XSS attacks in PHP we should filter all input we receive from outside sources. We can update our code to the below:

In PHP we can use the htmlspecialchars function to escape output. Our code to output the comments can be updated to the below:

Notice that we're not escaping the comment only, but also the username.

Key Takeaways

  • XSS is not unique to PHP, but a security threat to all non trivial applications.
  • In PHP, we can guard against XSS by filtering input and escaping output.
  • Cross site scripting is most commonly the injection of Javascript but can also be HTML or CSS.

Further Reading

To learn more, read about input filtering in PHP and output escaping.