I've been working off of some example code for logging into a database, and the author has provided two functions, for making entered data safe for the DB, with little explanation for why which is used where. I'm trying to figure out if it's a redundancy, and whether or not I shouldn't be using one of them at all, because it looks much... um... lighter in what it does.
Here's the first:
/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
$str = StripSlashes($str);
if($remove_nl)
{
$injections = array('/(\n+)/i',
'/(\r+)/i',
'/(\t+)/i',
'/(%0A+)/i',
'/(%0D+)/i',
'/(%08+)/i',
'/(%09+)/i'
);
$str = preg_replace($injections,'',$str);
}
return $str;
}
function StripSlashes($str)
{
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return $str;
}
And now the second:
/* No explanation whatsoever... */
function SanitizeForSQL($str)
{
if( function_exists( "mysqli_real_escape_string" ) )
{
$ret_str = mysqli_real_escape_string($connection, $str);
}
else
{
$ret_str = addslashes( $str );
}
return $ret_str;
}
The first code (which appears much more useful) looks like it's only used once when collecting the posted form fields into an array:
function CollectRegistrationSubmission(&$formvars)
{
$formvars['Email'] = Sanitize($_POST['Email']);
}
And the second is used pretty much any time anything is placed into a table field in the database or pulled from the SESSION data, such as:
$qry = "SELECT * FROM sessions WHERE Email='".SanitizeForSQL($Email)."'";
/* or */
$Email = SanitizeForSQL($_SESSION['email_of_user']);
My main concern is this seems redundant, but maybe that's because I don't understand it. Is there really a reason you would have to do both of these?
$formvars['Email'] = Sanitize($_POST['Email']);
$qry = "SELECT * FROM sessions WHERE Email='".SanitizeForSQL($formvars['Email'])."'";
So,
what's the difference?
Should I only be using one of these?
Should I be using something else entirely in one or both of these places?
Thank you for any light you can shed on this!