Link to home
Start Free TrialLog in
Avatar of Chimeraza
ChimerazaFlag for South Africa

asked on

SQL Injection protection

I am trying to create a function that validates/checks a string (submitted from a form via php) to ensure that it is safe to plug into a mysql database.  In a nutshell a complete sql-injection protection function.

I have included what I have so far...  would appreciate any advice on whether the function is sufficient or if there is anything else I am forgetting.  Any code or modifications would be greatly appreciated!
//SQL Injection protection
function mysql_prep($value) {
	$magic_quotes_active = get_magic_quotes_gpc();
	$new_enough_php = function_exists("mysql_real_escape_string"); //i.e. PHP >= v4.3.0
	
	if($new_enough_php) { // PHP v.4.3.0 or higher
		//undo any magic quote effects so mysql_real_escape_string can do the work
		if($magic_quotes_active){$value = stripslashes($value);}
		$value = mysql_real_escape_string($value);
	
	} else {	// before PHP v4.3.0
		//if magic quotes not on - add slashes manually
		if(!$magic_quotes_active) {$value = addslashes($value);}	
		//otherwise slashes already exist
	}
	
	return $value;	
}

Open in new window

Avatar of edster9999
edster9999
Flag of Ireland image

That will cover the escaping of nasty characters that people might inject.

I also like to keep a check on the value - but that might not be of use if this is a very generic function.
If it does have a defined use (like taking in fields for name and address) then it would be nice to limit the length to stop people trying to find buffer overflows.
The simple way of doing this is to use something like
$value = substr($value, 0, $max_length);
You can also check the content of the sting.  If you are expecting a single digit verify it is that using maxlength=1.
All of this doesn't work if you are keeping it generic.  It might be worth using some of it outside the function either in another function for checking certain forms or in the main procedure after you have your values.

Avatar of Chimeraza

ASKER

Sorry for the delay in my response...
yeah it is a pretty generic function...perhaps I could set a max limit on it to prevent buffer overflows..

I don't really know anything about buffer overflows besides what they are. What would be a good limit to use?
Would I still use this code:
$value = substr($value, 0, $max_length);

Also what happens if you use substr($value, 0, 50) if the field is only 20 chars long...will it give an error?

Thanks for your prompt response!
ASKER CERTIFIED SOLUTION
Avatar of edster9999
edster9999
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks so much!  Was a great help.