Karem
Karem

Reputation: 18103

php: grabbing user info from database, is this code secure?

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

Upvotes: 0

Views: 150

Answers (3)

avpaderno
avpaderno

Reputation: 29679

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.

Upvotes: 0

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 4

Mikulas Dite
Mikulas Dite

Reputation: 7941

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

Upvotes: 2

Related Questions