Utility Function for Preventing SQL Injection

Whenever you are taking data from a URL or the payload of an HTTP request and jamming it into a SQL query to run, you have to be mindful of SQL injection attacks.  Fortunately with PHP, it is rather easy to avoid.  PHP provides us with two functions for cleaning up incoming data: stripslashes() and mysql_real_escape_string().  According to the documentation, we have to be careful how we use them however.  Below is the code for a utility function I use to condition inputs before putting the data into any SQL queries:

function cleanValue($value) {
if(get_magic_quotes_gpc()) {
$value = stripslashes($value);

if(!is_numeric($value)) {
$value = mysql_real_escape_string($value);
return $value;

This function checks to see if the magic_quotes_gpc setting is enabled.  If it is, we have to use stripslashes() to strip out the escaping slashes added by that module.  Then if the value isn’t numeric, we use mysql_real_escape_string() to clean it up.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: