Today will be how to secure your website from XSS injections. Injections are ways for hackers to break your website. Fortunately, they are easily prevented with a few lines of code.
What are injections?
Injections are when you allow users to submit anything to your site without filtering the data. It's when you allow users to submit forms that enter data into your database or display it on your web page.
What is an XSS injection?
What can XSS do?
Am I vulnerable to XSS right now?
To find out if you're currently vulnerable to XSS right now, throw this little piece of code on anything that that will display your data. Forums, blogs, comments, ect... View the page where you display the data and if you get a pop up message, you are vulnerable to XSS.
<script>alert("You got hacked!");</script>
How do I stop XSS injection?
It's pretty easy actually; one line of code will do the trick. PHP has a built in function that converts all HTML tags to their code form. Browsers will display this code for its literal meaning without processing it. This will protect you against most XSS attacks. htmlEntities encodes all characters to their HTML counterparts. The second parameter, ENT_QUOTES, encodes single quotes since the function by default allows single quotes to pass through.
$user_data = '<script>alert("You got hacked!");</script>'; // Browsers see <script>alert("You got hacked!");</script> // Users see <script>alert("You got hacked!");</script> echo htmlEntities($user_data, ENT_QUOTES);
What other types of injections are there?
The most common are XSS, SMTP and SQL injections. SQL injection is when hackers try to manipulate your database. I'll dedicate an entire tutorial to SQL injection in a later tutorial. SMTP is mail injection and I'll talk about it in the mail tutorial that's coming soon.
Go through your code and patch up anything that has a security hole. You should always escape anything that users are allowed to touch before displaying it on the page. See you next time on PHP Trainee!