Preventing Cross-Site Scripting (XSS) in PHP

Cross-site scripting (XSS) is a type of vulnerability found in web applications. Occurs when a web application gets data from a user and makes use of them without validating, checking, encoding or filtering them. This vulnerability enables attackers to inject malicious client-side scripts into a trusted web site. The end user’s browser will execute the script because it comes from a trusted source thus allowing the script to steal sensitive information such as cookies and session tokens.

XSS example (save it as test_xss.php):

1
2
3
4
5
6
7
8
<html>
<head>
<title>Hello World</title>
</head>
<body>
Welcome, <?php echo $_GET['username']; ?>
</body>
</html>

Open your browser once more and type in the url bar:
http://localhost/test_xss.php?username=admin
and then
http://localhost/test_xss.php?username=adminalert(‘hello!’);
In the second example you will see a popup window saying hello!

How to prevent it in PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
function clearText($tainted_data){
	//strip tags from data
	$tainted_data = strip_tags($tainted_data);
	//convert all characters into html equivalent
	return htmlentities($tainted_data, ENT_QUOTES, 'UTF-8');
}
?>
<html>
<head>
<title>Hello World</title>
</head>
<body>
Welcome, <?php echo clearText($_GET['username']); ?>
</body>
</html>

Open your browser and type in the url bar:
http://localhost/test_xss.php?username=adminalert(‘hello!’);
In the second example you will not see the popup window. XSS vulnerability prevented!

Leave a comment