Firstly let me tell you that about 85% of protection methods are done with 2 functions.
Firstly if someone sends some data to your site such as $_POST['name']
, and you wish to use this value back on html side such as <p>The following string: {$_POST['name']} is invalid</p>
then you should ALWAYS make sure that that value has been through htmlspecialchars, this will protect most of XSS Attempts
Next is injection, if the value of $_POST['name']
is going into your database just make sure that you use mysql_real_escape_string on that value.
that will give you 100% protection from sql injection, but all that means is your db cannot run commands from the user, that dont mean that the text is what it should be.
The functions that you should always use before inserting data into your database are
This is called Validation and is only needed for yout to make sure the data the user is submitting is what you want such as filter_var would be used to validate that the email they entered is an email and not just some blah blah
What i usually tent do do is to run a clean function to make sure that all imputed data is clean with htmlspecialchars
example:
function clean($array)
{
foreach($array as $key => $val)
{
if(is_array($val))
{
$array[$key] = clean($val); //Recursive
}else
{
$array[$key] = htmlspecialchars($val, ENT_QUOTES);
}
}
return $array;
}
Then do the following to make sure that your safe from XSS:
$_GET = clean($_GET);
$_POST = clean($_POST);
So if someone tried to submit <a href='test'>Test</a>
then the value would be converted to <a href='test'>Test</a>