Is this code sufficient to protect me from SQL injection attacks, and PHP injection attacks?
I have this function in an include file of functions:
function strclean ($string) {
$outstr = '';
if (strlen ($string) > 0) {
$ix = 0;
$char = substr ($string, $ix, 1);
// strip leading spaces
while ($char == ' ') {
$ix = $ix + 1;
$char = substr ($string, $ix, 1);
}
// disarm naughty characters
while ($ix < strlen ($string)) {
$char = substr ($string, $ix, 1);
if ($char == '<') $char = '<';
else if ($char == '>') $char = '>';
else if ($char == '"') $char = '"';
else if ($char == '&') $char = '&';
else if ($char < chr(20)) $char = '';
$outstr = $outstr . $char;
$ix = $ix + 1;
}
// strip trailing spaces
while (substr ($outstr, strlen ($outstr) - 1, 1) == ' ' && strlen ($outstr) > 0) {
$outstr = substr ($outstr, 0, strlen ($outstr) - 1);
}
$outstr = mysql_real_escape_string ($outstr);
}
return $outstr;
}
Later on in my page, I have various strings returned from form input such as this example:
$username = strclean ($_POST['username']);
$password = strclean ($_POST['password']);
And even later, I have the following SQL:
$result = mysql_query ('SELECT * FROM users WHERE
username = "' . $username . '"', $dbconn) or die (mysql_error());
I don't search for username and password together in the query. A few lines after this, I check for a valid password like this:
if ($rowsfound == 1) {
$userrow = mysql_fetch_array ($result);
$userword = $userrow ["password"];
if ($userword == $password) {
// logon
}
else {
// incorrect password
}
}
else if ($rowsfound == 0) {
// unknown user
}
else {
// something strange happened! possible sql injection attack?
}