Will this prevent sql injections?

jlknauff

New member
Aug 25, 2008
237
1
0
Code:
  $input = strip_tags(str_replace(array('/','.',':','"'),' ',$input));

You shady bastards can probably tell me if I'm missing something here? Or do I have all my bases covered?
 


I'm no expert, but I think you would want to check to see if quotes etc are already being escaped with magic quotes before replacing stuff, and doing it based on the response of get_magic_quotes_gpc() . Could be way off, still kind of a noob at this stuff.

Something like this I think...
Code:
if(get_magic_quotes_gpc()){      
   $input = strip_tags(str_replace(array('/','.',':','"'),' ',$input));     
   }else{     
   $input = strip_tags(str_replace(array('/','.',':'),' ',$input));     
}
 
The safest way to stop crap coming through is to take the opposite approach. Instead of listing characters to remove - only allow certain ones through.

<?php $good_stuff = preg_replace('/[^a-zA-Z0-9 ]/i', '', $bad_stuff); ?>

Edit to taste.
 
PHP is pretty safe if you follow standards. Make sure if you are using an older version of PHP you have "Magic_Quotes" turned off. This adds pointless overhead and makes your coding more open for exploits. Then simply use mysql_escape_string as explained above any time you are adding something. Even if it's an INT type, still escape with quotes if it's data you are not positive can't be exploited:

'field="'.mysql_escape_string($_POST['name]).'"';
 
If you're ever accepting an integer, and that integer is not already run through a regex (for example, mod_rewrite) then you need to cast it as an integer.

For example:
Code:
$id = (int)$_GET['id'];
$id = intval($_GET['id']);
 
Use this :

Code:
function Sanitize($data){
    if(get_magic_quotes_gpc())
    {
        $data = stripslashes($data);
    }
    $data = mysql_real_escape_string($data);
    return $data;
}