Forum Moderators: coopster

Message Too Old, No Replies

Checking for Existence of PHP Session

is it possible?

         

FourDegreez

9:25 pm on Oct 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



My understanding is that there is a cost associated with creating sessions, so is there an optimal way of checking for the existence of a session without needlessly creating a new one?

My idea of determining if there is an active session is to call session_start() and check to see if an expected value (user_id, for example) is set. But the act of calling session_start() will begin a new session if one did not exist, correct? This is what I'd like to avoid.

What I'm looking for is something like
if (session_exists()) {
   session_start();
   $user_id = $_SESSION['user_id'];
}

PHP_Chimp

9:48 pm on Oct 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The session_start() call just tells php that it should be looking for sessions. It wakes up php's session side of things if you like. So if you want active sessions then you need to call session_start().

If you are storing session information in cookies then you could always look for $_COOKIE['session_name'] to see if it is there. Then decide to start or not. If you are using url id's then look in the $_GET array for PHPSESSID or whatever your session_name is set to.

You may be able to use session_id() [uk.php.net] for what you are looking for.

If you are starting sessions based on user supplied info like cookies/url's then be very very careful about people fixing/poisoning/mucking your your sessions. As with everything that users can supply treat it as evil until it have been cleaned, validated and checked...and even then it may well just be safer to call session_regenerate_id() [uk.php.net]or just start a new session.