Jump to content

Simple best-practice idea to prevent sql injections


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]; }




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']);

Link to comment
Share on other sites

- 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.

Link to comment
Share on other sites

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);


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

Edited by Stefany93
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • 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.