PHP Security: Protecting Your PHP Projects From XSS Attacks

Its a year now when I was still a cool newbie in PHP thought am not yet expert now 🙂 I was coding something like a forum where users can post and other users can read and comment. I hosted the project and something just hit my head “What if a user posts <script>alert(‘hello’)</script> will it work?”.

Actually it did work! About a half percents of PHP Projects hosted online are vulnerable to this and without protection it is also vulnerable to the XSS Attact (Cross-Site Scripting), people are much ignorant of this.

What is XSS and how does it work?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications.  XSS enables attackers to inject client-side script into Web pages viewed by other users. [Wikipedia]

Now lets write a program to accept user’s input and return it.

<html>
<head>
<title>XSS Example</title>
</head>

<body>
<form action="" method="post">
<?php
if(isset($_POST['example']))
{
echo $_POST['example'].'<br/>';
}
?>
<input type="text" name="example" />
<input type="submit" value="Submit" />
</form>
</body>

</html>

In the input box just put in some thing like this <b>Hello</b> and submit, it turn bold right? Now when I input something like this:

<script>alert('Hello')</script>

Definitely it will show me a JavaScript Alert box, so if am making an input in your hosted site and input this in my profile. Any other user that visits my profile must see an alert button which a more advance JavaScript coder can write a script to show all cookies available in that user’s browser which can lead to Session Hijacking.

How can I protect my Project from this?
Well, PHP made everything easier with some built in function that am gonna list below

  • The htmlentities() : This function converts HTML element to entities which the browser won’t inteprete it but view it. Example below:

<html>
<head>
<title>XSS Example</title>
</head>

<body>
<form action="" method="post">
<?php
if(isset($_POST['example']))
{
echo htmlentities($_POST['example']).'<br/>';
}
?>
<input type="text" name="example" />
<input type="submit" value="Submit" />
</form>
</body>

</html>

  • The htmlspecialchars(): This is exactly the same with the htmlentities() but with small changes I can’t really explain now 🙂 Read more

I guess this now solves your problem 🙂

Posted in: