- Try to validate as much if not all input from users. This is very tedious and time consuming but taking some time to learn regular expressions really helps... Research regular expressions cheat sheet.
When getting information from a url or a form always use the $_ set of variables
$_POST for getting information from forms.
$_GET for getting information from urls
Example of $_POST:
post-exp.php
echo 'My name is: '.$_POST['myname'].'
';
?>
Example of $_GET:
A few examples for validation:
email-test.php
if(!ereg("^+?[a-zA-Z0-9](([-+.]|[_]+)?[a-zA-Z0-9]+)*@([a-z0-9]+(.|-))+[a-z]{2,6}$", $_POST['email']))
{
die('
}
else
{
echo 'Valid email';
}
?>
Here is an example of a very basic regular expression validation:
(Understand the code that actually post to this I did not give sense code very simular is above.
if(!ereg("^[a-zA-Z]+[0-9a-zA-Z_-]{4,31}$", $username))
{
die('
*Requires: 5 to 32 characters (dash & underscore allowed)')
}
else
{
echo 'Good username';
}
if(!ereg("^[0-9a-zA-Z]{5,32}$", $password))
{
die('
*Requires: 5 to 32 characters or numbers')
}
else
{
echo 'good password';
}
And, my last and very dirty validation script is below:
function sqlextraction($var)
{
// Replaces ' with ' (its ascii representation)
$var = str_replace('"','"',$var)
// Replaces " with " (its ascii representation)
$var = str_replace(''',''',$var)
return $var;
}
function securestring($var)
{
return sqlinjection(str_replace('../','',$var))
}
The two above functions will take care of any sql injection problems with mysql and will also take care of any file issues with trying to go to a file under directories... There are other ways to make this script not work but then not everything is 100% smile
Here are just a very small amount of good validation and security tips.
I hope others will supply more information and other suggestions on security.