Zend - The PHP Company




Security

Add Code


Avoid SQL injection  

Type: code fragment
Added by: bto
Entered: 19/08/2004
Last modified: 08/12/2003
Rating: **** (4 votes)
Views: 11239
This is a function which will format the passed string depending of it's specified to be a number or a string, in order to avoid problems with SQL injections in scripts.


<?php
function ToDBString($string$link$isNumber=false)
{
    
//If $isNumber==true we are specting a number
    
if($isNumber)
    {
        
//A correct number must be composed of:
        // - Zero or more integers followed by a decimal point and one or more integers (i.e.: .9 (0.9) or 9.9)
        // - One or more integers followed by a decimal point. (i.e.: 9. (9.0))
        // - One or more integers (i.e.: 999)
        
if(preg_match("/^d*[.,']d+|d+[.,']|d+$/A"$string))
        
//If it's a correct number we change the colon, quote or point ("'", "," or ".") by a decimal piont.
            
return preg_replace( array(
                                       
"/^(d+)[.,']$/"     //9.
                                       
"/^(d*)[.,'](d+)$/"  //.9 or 9.9
                                      
),
                                 array(
                                       
"\1."                ,
                                       
"\1.\2"
                                      
)
                                 , 
$string);
        else
        
//If it's not a correct number we show ERROR
            
die("ERROR: Not a number"".$string.""");
    }
    else
     
//If $string is a string ($isNumber==false) we return "'$string'" correctly escaped (in this version I also strip HTML tags and modify some things in the string, change it if you wish).
     
return "'".mysql_real_escape_string(htmlentities(strtoupper(trim(strip_tags($string)))), $link)."'";
}
?>


Usage Example


$link=mysql_db_connect("HOST", "USER", "PASSWORD");

$foo=ToDBString($_POST["string"], $link);
$bar=ToDBString($_POST["number"], $link, true);

$result=mysql_db_query("DATABASE", "SELECT * FROM secret WHERE foo LIKE $foo AND bar=$bar", $link);

//If $_POST["foo"] or $_POST["bar"] are a string of this kind: "'' OR 1=1" and we don't use ToDBString we will show all the info of the table!!!!


Rate This Script





Search



This Category All Categories