--- title: Cross Site Scripting --- ## Cross Site Scripting Cross Site Scripting is a type of vulnerability in a web application caused by the programmer not sanitizing input before outputting the input to the web browser (for example a comment on a blog). It is commonly used to run malicious javascript in the web browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the web application. ### 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 ` ``` ### Defending your website from cross site scripting attacks in PHP In PHP there are two primary functions, `htmlspecialchars()` and `strip_tags()`, built in to protect yourself from cross site scripting attacks. The `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** ```PHP alert('Cross Site Scripting!');"; echo htmlspecialchars($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()` function you have to be more careful, this function does not prevent the user from including javascript as a link, you'll have to sanitize that on our own. **strip_tags() code example** ```php alert('Cross Site Scripting!');"; $allowedtags = "

"; echo strip_tags($usercomment, $allowedtags); ``` **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. ```PHP ``` #### More Information: * OWASP Wiki - Cross Site Scripting * php.net strip_tags() manual * php.net htmlspecialchars() manual * MDN - Content Security Policy (CSP)