Thread: SQL Injection
View Single Post
Old 06-25-2008, 07:44 PM   #4 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

In the past, before I switched over to Zend Framework, I ran all my PHP variables, to be used in a MySQL statement, through the following function. I'm not sure if it's actually 100% secure, but it seemed to be. I think Salathe, a while ago, pointed out some problems regarding different file-types, such as boolean values, but I don't believe anybody actually discovered any such major flaws.

It'll serve as a good base nonetheless, for if you wish to add onto it, or switch some things around, or merely use it as a reference.

php Code:
function mysql_parse_value($value, $strip_tags=true, $allowable_tags=null)
{
    if (is_array($value))
    {
        return
    }
   
    if (get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
         
    if ($strip_tags)
    {
        $value = strip_tags($value, $allowable_tags);
    }
       
    if (!is_numeric($value))
    {
     $value = "'" . mysql_real_escape_string($value) . "'";
    }

    return $value;
}

I did use it in conjunction with sprintf, as you mentioned. This function places in any quotes for you, and so you shouldn't actually put in any quotes into sprintf's first argument.

To give an example:

php Code:
$szMyVar1 = 'TalkPHP.com';
$szMyVar2 = 'TalkRSI.com';

$szSQL = sprintf
(
    "SELECT * FROM myTable WHERE myColumn = %s OR myColumn = %s",
    mysql_parse_value($szMyVar1), mysql_parse_value($szMyVar2)
);
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote