views:

216

answers:

3

I was told in a previous question that my query is prone to SQL injections.

get_stats = mysql_query("SELECT * 
                               FROM visitors 
                              WHERE site='$_GET[site]' 
                                AND date BETWEEN '$start_date' AND '$end_date' ");

What would be the easiest way to approach this problem? And do you have some further reading on the subject of injections? (something that I might miss on Google). Thanks!

+14  A: 

Use Prepared Statements.

In most cases, Prepared Statements do the job of combining your query with your parameters, in a safe manner.

RichieHindle
Thanks!
Norbert
+1  A: 

mysql_real_escape_string is the most basic and easiest form of security here.

Ben Shelock
this won't save you in all cases... suppose the column being compared against is a number, in which case the variable is unquoted. That escape function won't do anything to prevent "5 or 1=1" (for example) from being put in there, AFAIK.
rmeador
+7  A: 

$_GET['site'] is a value that comes straight from the URL in the browser which means a user could easily change this value to anything they want, you should check/sanitize that value, all values actually before sending it to a database.

Something like this would be a start, could still use more work and there is many ways of doing it, I would create a custom function/class to easily pass all variables through sitewide which can simply repetitive stuff like this

$site = mysql_real_escape_string($_GET['site']);
$start_date = mysql_real_escape_string($start_date);
$end_date = mysql_real_escape_string($end_date);

get_stats = mysql_query("SELECT * FROM visitors WHERE site='$site' AND date >= '$start_date' AND date <= '$end_date' ");
jasondavis
Don't forget to escape `start_date` and `end_date`, as well.
Ben Blank
you don't just want to sanitize before sending to the database... sanitize before you do ANYTHING with it! SQL injection is just one (common) problem that you run into with this sort of thing, but you can also get a host of others, such as HTML and JS injection...
rmeador
good points, I updated
jasondavis