0

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

Karem
  • 17,615
  • 72
  • 178
  • 278

3 Answers3

4

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.

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 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 Aug 06 '10 at 15:38
  • @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 Aug 06 '10 at 15:40
  • 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 Aug 06 '10 at 15:43
  • @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 Aug 06 '10 at 15:45
2

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
  • 7,790
  • 9
  • 59
  • 99
0

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.

apaderno
  • 28,547
  • 16
  • 75
  • 90