Jump to content

How to sanitize user input to prevent SQL injection?


gamefreak13

Recommended Posts

I am so sick of reading about sql injection. Every article recommends a different way of preventing sql injection. There has to be a final answer. An answer that works in all scenarios and has no negative impact and doesn't require a step before and after (e.g. add/strip slashes).

 

A few include:

 

addslashes

stripslashes

trim

mysql_real_escape_string

strip_tags

htmlentities

 

So what is it? If I understand things correctly, mysql_real_escape_string is the best single one to use but isn't perfect. So what is the perfect combination? I am trying to sanitize user input for registration/login which queries my database. The site is more likely than most to receive script kiddies trying to do harm, so I'd like to figure this out before I release the site.

 

Also.. this is what I have right now (found this snippet online). Why would I need to to use stripslashes? If anything, wouldn't I need addslashes instead?

 

function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
	$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}

How you avoid injctions is your own choice based on the best output for what you need.

 

You could create a function which would keep all input constant throughout your site.

 

function escape_string($string) {
     $string = htmlspecialchars(mysql_real_escape_string));
     return $string;
}

 

There is no right way to do it.

I guess I need to create two different filter functions. One to filter so I put the user input in to a sql query (remove slashes and stuff). The other is to filter the input that is shown on the page (remove html stuff).

 

This is what I got for the sql portion. Opinions welcome.

 

function clean($string) {

// IF MAGIC_QUOTES_GPC IS ENABLED WE MUST STRIPSLASHES
if(get_magic_quotes_gpc()) {
	$string = stripslashes($string);
}

// IF MYSQL_REAL_ESCAPE_STRING IS AVAILABLE, USE IT!
if(function_exists("mysql_real_escape_string")) {
	$value = mysql_real_escape_string($string);
}

// FOR PHP VERSION < 4.3.0 USE ADDSLASHES
else {
	$value = addslashes($string);
}

return trim($string);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.