I’m encountering something weird and I don’t know why it is happening!
I have a URL like:
http://mysite.com/users/USER_ID
this user id could be INT and could be STRING, it’s something like Facebook page addresses, if you call the page with page ID it loads it, also you could call it with page name like “my_page_name”
So imagine a user which it’s ID is 1 and it’s address is my_name
On my php page I need query db, but before that I need to know which column to look, id or page_name
So I came with this solution:
<?php
$id = $_GET['id'];
$id_inted = intval($_GET['id']);
if($id == $id_inted){
// The column which I should look into is id
$column = 'id';
}else{
// The column which I should look into is page_name
$column = 'page_name';
}
$query = mysql_qyery(SELECT * FROM members WHERE $column = '$id');
?>
So I tested it, but the results is weird, even if I call this URL:
http://mysite.com/users/page_name
This happens: $column = 'id';
I opened a new test page:
<?php
$real_string = 'abcdefg';
$string_inted = intval($real_string);
echo "Real String is: " . $real_string . "<br />";
echo "The same string as int is: " . $string_inted . "<br />";
if($real_string == $string_inted) echo "Weird!"; else echo "Fine...";
?>
and the results:
Real String is: abcdefg
The same string as int is: 0
Weird!
Why this is happening?
Thanks in advance.
PHP is really “wired” with so called type-juggling. It is the most error-prone part of most PHP-scripts. As such, you should always stay on the safe side and use the most robust check. For example
intval("twelve")will return 0, which is a valid integer. But also considered “false”:print if (intval("one")) ? "yup" : "nope"will print “nope”.In this case, using
intval, in combination with a check if the integer is larger then zero, should do the trick:Or, shorter:
Aso note that $_GET[“id”] might not be set, which would throw a notice in your code.
And last, but certainly not least: the SQL-injection:
?id=LittleBobby';Drop table users.edit As commentor points out, there was a logical flaw in my code, stemming form the fact I tested it in phpsh only. I refactored it from using
is_int()tointvaland> 0. In a web-environment, $_GET[“id”] is always a string; no matter what. Henceis_int()will always returnFALSE.