What is XSS and how to prevent it in PHP?
XSS (Cross Site Scripting) is an attack where a visitor puts JavaScript code in your page, for example in a comment, and that code runs in the browser of other visitors. It can steal cookies, show fake forms or change the page.
The main fix is to escape the output. Convert special characters of user data to safe HTML before you print it, using htmlspecialchars().
<?php
$comment = "<script>alert('Hacked')</script>";
echo htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
?>
Output:
Tutorials Class - Output Window
<script>alert(‘Hacked’)</script>
The browser shows this as plain text and does not run it.
- Escape every user value when you print it, always with ENT_QUOTES and UTF-8.
- Validate input on the server (for example allow only numbers in an age field).
- Use the
HttpOnlyflag on cookies, so JavaScript can not read the session cookie. - Add a Content-Security-Policy header for extra protection.
More tips are in PHP Security Tips.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |