Skip to main content
ApachePHP-MySQL

PHP XSS Example and Prevention

By April 30, 2014September 12th, 2022No Comments

I think very often cross-site scripting or XSS attacks are mentioned especially in relationship to desktop courses and how browsers can help prevent them but they do not give details of what they are or how they work. So in the video we will demonstrate a simple XSS attack using a PHP page and how to prevent the code injection through PHP forms.

XSS attacks make use of injecting additional code that is past through as part of the query portion of the URI. If a user can submit from a form to a back end PHP script there is the chance of an XSS attack. The user would add more than plain text to the field they are editing. This is then passed back and interpreted perhaps as code on the server or browser.

In out example the user submits a vlaue on a form such their name and that is display back, but if we add HTML tags, including the <script> tag then they are process as HTML when sent back to the browser. In this way a script can run in the user’s browser. Perhaps hijacked from another site.

The user is meant to just add Fred to the field, instead they add

<script>alert(‘XSS’)</script>

When PHP prints this information back to the browser the script now runs. this just display a dialog but it could be a lot worse.

The PHP code that is running will look similar to this:

echo $_POST["name"];
To sanitize  the date before sending it to the browser we can change the code to this:
echo htmlentities($_POST["name"]);
In this way they tags then are replaced as literals so the tags print rather than being processed. The printed result would be literally as the user had typed it without HTML processing.