tags:

views:

585

answers:

4

Hi, i am fetching a text from mysql database and i get it by ID in the url:

site.php?id=1 and so on

What is considered to be most safe to prevent sql injection and stuff. Is this way correct:

<?php
$news_id = $_GET['news_id'];

if(!is_numeric($news_id)) die('Wrong');

//mysql_query and stuff here
?>

OR this way:

<?php
$news_id = $_GET['news_id'];

if(!intval($news_id)) die('Wrong');

//mysql_query and stuff here
?>
+1  A: 

is_numeric is not a good way to check it,

$number = "4"; // string ? int ?

int_val doesn't return true or false. so you can't use it like you wrote. try this one

if(int_val($news_id) === (int)$news_id){
//code goes here
}

or

if(int_val($news_id) == $news_id){
//code goes here
}
Ahmet Kakıcı
What is the legal range of numbers for your id? Does it start with zero or one?
James Black
+3  A: 
$news_id = (int)@$_GET['news_id'];
if ($news_id <= 0) die ('Wrong');

Assuming news_id is positive (>0).

pingw33n
+1  A: 

If you use intval you won't be able to use news_id=0, because intval will always return 0 if news_id isn't a number. is_numeric is more suitable and safer in your case.

OneOfOne
Chances are, `news_id` is a generated column that will never contain 0. If that's the case, then there's no harm in using intval( $id ) in the query; if the request contained a bad identifier, then you'll end up displaying a "not found" error, which is perfectly acceptable for a bad request. Alternatively, of course, if 0 is a value that's never used, then you can test the output and throw up a different error ("please provide a valid identifier") rejecting the request.
Rob
+4  A: 

Why not just use a prepared statement, which is the correct way to deal with sql injection attacks.

But, use intval to turn the string into an integer, and then just put that into your prepared statement, and you will be protected, as, the int value may be a zero or negative so nothing will be returned from your query.

James Black