Jump to content

Simple best-practice idea to prevent sql injections


tibberous

Recommended Posts

I normally hate best practices, but this one I came up, so it's less bad.

 

Basically, you create a few functions like:

 

function ireq($x){ return intval($_REQUEST[$x]); }

function req($x){ return mysql_real_escape_string(trim($_REQUEST[$x])); }

function unescaped($x){ return $_REQUEST[$x]; }

 

Next, NEVER use $_REQUEST

 

Now, to check your site for SQL injection holes, you can just search for $_REQUEST and "unescaped(". You can even use this method to slowly rewrite other peoples code, by replacing each $_REQUEST and making sure the proper characters are escaped.

 

Has the added benifit of being MUCH fast to type - $i = req('i') vs $i = mysql_real_escape_string($_REQUEST['i']);

- Besides unescaped() you could just as easily search for code using $_REQUEST directly and fix that.

 

The advantage to using unescaped is that it at least shows you looked and made a consious decision to use unescaped data. Also, if you implement others code, you can replace their $_REQUEST's as needed.

You shouldn't be using the old mysql_* functions at all. They've been soft deprecated. Instead, use either MySQLi or PDO with prepared statements. That will protect you from injection attacks.

 

Agreed 100%

You shouldn't be using the old mysql_* functions at all. They've been soft deprecated. Instead, use either MySQLi or PDO with prepared statements. That will protect you from injection attacks.

 

I agree, with prepared statements, SQL injections are almost 100% eliminated.

 

$username = 'Longstreet';
$query = $db->prepare("INSERT INTO names(username) VALUES(:username)");
$query->bindParam(':username', '$username', PDO::PARAM_STR);
$query->execute();

 

When I first started using PDO, I kept forgetting to execute the query and I can't tell you how many hours I had spend searching why the heck wasn't my code working :D

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.