tags:

views:

23

answers:

4

When a user logs in should I sanitize there logged in $_SESSION['user_id'] user id or not? for example, like in the following code below.

mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_SESSION['user_id'])));
+2  A: 

Session data is stored server-side, so it should be sanitized before being added to $_SESSION in the first place.

Ignacio Vazquez-Abrams
So there is no need to sanitize the `$_SESSION` when I retrieve it from the database?
phps
As long as you sanitized the data before putting it in the session, it's safe from that point forward.
Charles
+1, plus something that _needs_ to be done: on logging you should regenerate a different session_id to avoid session fixation.
Wrikken
A: 

You could always use session_id() instead which should work.

webdestroya
A: 

not really an security expert but you could cast it anyway (int) $_SESSION['user_id']

A: 

You have absolute control over what you put in $_SESSION, so there are some types of sanitation checks that should be done prior to put the the values in $_SESSION (e.g., did the user submit an array, is it longer than what's permitted, etc.).

However, of you're asking if you should escape the strings before passing them to the database, the answer is yes (a user name that's valid may or may not contain the character ', for instance). Better yet, use prepared statements if possible.

Artefacto