tags:

views:

44

answers:

3

Hello. So i was wondering if i this is OK or if theres another better and secure solution to grab info from the database.

if (isset($_SESSION['user_id'])) {
$string = mysql_query("SELECT * FROM users WHERE id = '$_SESSION[user_id]'");
$v = mysql_fetch_array($string);
}

Because I was thinking maybe its possible to hack the "session" and change user_id to another and woops they get access to any user...

Thank you

+2  A: 

I suggest escaping the user_id, just to be sure. You should also test if any rows were found (optional, depends on usage).

Mikulas Dite
+4  A: 

This depends on how the user_id gets into the Session in the first place.
As a rule of thumb, you should never place any unsanitized values into a query.
You should at least use mysql_real_escape_string. Even better would be not to use the old and outdated mysql extension but mysqli's prepared statements.

Gordon
the user_id gets into the session at the login:$_SESSION['user_id']= $id; i forgot the escape string, should i do anything to the session lines too?
Karem
@Karem yes. That rule of thumb above really applies to any outside input. Even if you think it might be save: sanitize all user input.
Gordon
what does sanitize mean, could you please explain thank you.
Karem
@Gordon and by "really applies to any outside input" do you mean that i can apply the mysql_real_escape_string to the $_SESSION['user_id']= $id; too? Or just to all my mysql_query()´s
Karem
@Karem no, just to the query of course. But do have a look at the [native Filter functions](http://de.php.net/manual/en/book.filter.php)
Gordon
A: 

Every data coming from the user should be filtered, and never used directly in a query; this would avoid SQL injection.

Suppose the content of $_SESSION['user_id'] is ' OR id = '12' //; the query would become SELECT * FROM users WHERE id = '' OR id = '12' //'. Supposing that the user account with ID 12 has particular permissions that allow the user to delete content from the site, you can imagine the consequences.

kiamlaluno