XSS Prevention

after briefly discussing XSS here, even though it was a bit messy, now it’s time to discuss how to prevent this bug from existing on our website

XSS can run / be executed because of loose <script> tags that are executed / rendered by the browser, therefore we manipulate the browser so it does not execute HTML tags that are input by users. But don’t worry, we’re not going to mess with the browser, just a little handling before user input is displayed on the website

example:

<?php
echo $_GET['q'];
?>

input : <script>alert("XSS")</script>
output: <script>alert("XSS")</script> // XSS popup will appear
for prevention we can use several existing PHP functions


<?php
echo strip_tags($_GET['q']);
?>

input : <script>alert("XSS")</script>
output: alert("XSS") // HTML tags will be removed
however the code above is still not enough to handle this XSS, why ?


<?php
echo '<input type="text" value="'.strip_tags($_GET['q']).'">';
?>

input : " onmouseover="alert('XSS')
output: <input type="text" value="" onmouseover="alert('XSS')">
with the input above, when the mouse hovers over the text input an XSS popup will appear
so how do we avoid bypasses like this ?


<?php
echo '<input type="text" value="'.htmlentities(strip_tags($_GET['q'])).'">';
?>

input : " onmouseover="alert('XSS')
output: <input type="text" value="&quot; onmouseover=&quot;alert(1)"> // quotes become &quot;

well in my opinion using those two functions is enough to prevent XSS on a website, but if a search field really needs the < and > characters we can use preg_replace() to remove all words containing XSS elements such as script, javascript, onerror, onmouseover, onload etc

what do you think? do you have other ways to avoid XSS? feel free to share in the comments