Is this a safe way to secure against sql injection?
Is this code 100% safe from sql injecti开发者_StackOverflow社区on:
$id = $_GET['id']
mysql_query('SELECT * FROM mytable WHERE id < ' . (int)$id);
or do I have to do this?
$id = $_GET['id']
mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id));
The query could still blow up if $_GET['id']
is empty, or (int)$_GET['id']
evaluates to empty. You'd end up with a syntax error in the query. It's not enough to blindly escape or type-cast a value and stuff it into a query. You have to check that the final "safe" value is actually safe and not just a wolf in grandma's clothes.
This article seems to be a good one in explaining how mysql_real_escape_string can protect you from SQL Injection, but it also explains its "holes"
http://www.webappsec.org/projects/articles/091007.shtml
This
mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id));
would be bad practice. If you want it to be a string, at least quote the string:
mysql_query('SELECT * FROM `mytable` WHERE `id`<"'.mysql_real_escape_string($id)).'"';
(and while you're at it, quote all field and table names as well, for things like id
might be or become reserved keywords at some point)
I would prefer the cast, if it is an integer. One argument for the string version would be that some day the id might be alphanumeric (as seen more and more often on a lot of websites).
I use sprintf
, mysql_query(sprintf('SELECT * FROM mytable WHERE id < %d', $id));
You should use parameterised queries. Then you don't need to worry about all that escaping. It also makes the SQL much easier to read. Oh and don't use select *, just select what you want.
No
you have to do this:
$id = mysql_real_escape_string($_GET['id']);
//put the escaped string in a $var, so your select statement stays readable
//this will help in debugging, and make **not** forgetting those vital quotes
//easier.
$query = "SELECT * FROM mytable WHERE id < '$id'";
// ^ ^always single quote your $vars
// ^ ^ and double quote the query
$result = mysql_query($query);
//and test to see if your query ran successful.
if (!$result) { //your query gave an error, handle it gracefully.
Then you're safe.
It is safe but you probably want to do
if(is_int($id)){
mysql_query('SELECT * FROM mytable WHERE id < ' . mysql_real_escape_string($id)); // just to be safe always to escape
}
精彩评论