PHP Function to prevent cross site scripting (XSS) attacks

PHP Function to prevent cross site scripting (XSS) attacks

PHP Function to prevent cross site scripting (XSS) attacks

I found in many supporting forums and discussions that newbies in PHP usually do not know what are XSS attacks and what they can do  to prevent.

Suppose you have created a commenting system and you have to get data from users and some evil users visited your site, batter if we call them hackers. they may use some traditional injection tricks to fix vulnerable code to your site in your commenting system or login system as

“><script language=javascript>setInterval
(“window.open(‘http://www.baddomain.com/’,’innerName’)”,50);
</script>

Or

http://www.itshacked.com/search/index.php?name=xss , there is every possibility that a hacker may try to inject some javascript.

http://www.itshacked.com/search/index.php?name=”><script language=javascript>setInterval
(“window.open(‘http://www.baddomain.com/’,’innerName’)”,50);
</script>

Like this there are numerous techniques, So inorder to prevent such XSS and MySQL injection attacks on your website feel free to use the function below which is written in php.

function cleanxss($input)
{
/// Prevents XSS Attacks www.itshacked.com
$search = array(
'@<script[^>]*?>.*?</script>@si',   // Strip out javascript
'@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
'@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
'@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
);

$inputx = preg_replace($search, '', $input);
$inputx = trim($inputx);
if(get_magic_quotes_gpc())
{
$inputx = stripslashes($inputx);
}
$inputx = mysql_real_escape_string($inputx);
return $inputx;

}

 

 

abhijeet on Facebookabhijeet on Linkedinabhijeet on Twitter
abhijeet
abhijeet
Abhijeet specializes in developing software. A full-stack developer and Entrepreneur, he takes an idea and crafts it into a beautiful product - front to back. He develops on the LAMP Stack (PHP, MVC, Web API, Perl, Python, Azure, AWS, Google Cloud) and utilizes AngularJS and Angular Material for a structured client. Abhijeet is a self-starter with experience working in remote, agile environments mainly focusing on the security constraints. This is the developer, Project Manager and Consultant you are looking for.