title: Cross Site Scripting
Cross Site Scripting
Example Cross Site Scripting Attack
A blog allows users to style their comments with HTML tags, however the script powering the blog does not strip out
<script> alert('Cross Site Scripting!'); </script>
Defending your website from cross site scripting attacks in PHP
In PHP there are two primary functions,
strip_tags(), built in to protect yourself from cross site scripting attacks.
htmlspecialchars($string) function will prevent an HTML string from rendering as HTML and display it as plain text to the web browser.
htmlspecialchars() code example
"<string>alert('Cross Site Scripting!');</script>"; echo htmlspecialchars($usercomment); $usercomment =
The other approach is the
strip_tags($string, $allowedtags) function which removes all HTML tags except for the HTML tags that you’ve whitelisted. It’s important to note that with the
strip_tags() code example
"<string>alert('Cross Site Scripting!');</script>"; $allowedtags = "<p><a><h1><h2><h3>"; echo strip_tags($usercomment, $allowedtags); $usercomment =
Setting the X-XSS-Protection Header:
In PHP you can send the
X-XSS-Protection Header which will tell browsers to check for a reflected Cross Site Scripting attack and block the page from loading. This does not prevent all cross site scripting attacks only reflected ones and should be used in combination with other methods.
"X-XSS-Protection: 1; mode=block"); header(
Writing your own sanitization function
Another option, if you would like more control over how the sanitization works, is to write your own HTML Sanitization function, this is not recommended for PHP Beginners as a mistake would make your website vulnerable.
Defending your website from cross site scripting attacks with a Content Security Policy
An effective approach to preventing cross site scripting attacks, which may require a lot of adjustments to your web application’s design and code base, is to use a content security policy.
Set a Content Security Policy as an HTTP Header
The most common way of setting a Content Security Policy is by setting it directly in the HTTP Header. This can be done by the web server by editing it’s configuration or by sending it through PHP.
Example of a Content Security Policy set in a HTTP Header
"content-security-policy: default-src 'self'; img-src https://*; child-src 'none';"); header(
Set a Content Security Policy as a Meta tags
You can include your Content Security Policy in the page’s HTML and set on a page by page basis. This method requires you to set on every page or you lose the benefit of the policy.
Example of a Content Security Policy set in a HTML Meta Tag
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">