note 88734 deleted from function.session-id by danbrown

From: Date: Thu, 05 Feb 2009 06:54:51 +0000
Subject: note 88734 deleted from function.session-id by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150245@lists.php.net to get a copy of this message
Note Submitter: Glen ---- Been PHP'ing for years. Always done more advanced session handling manually. Finally set up a simple site and decided to use PHP's built in session stuff..... omg.. Reading documentation and examples leads me to think that you can call session_id() (to get the value) before session_start() - to determine if a session already exists. But it doesn't! The SID constant doesn't exist either. Grrr.. You have to call session_start() before session_id() - otherwise session_id() always returns an empty string. But, as we know, session_start() will always create a session. What if you don't want to blindly create a session? Let's say you have a website and only require sessions for admins - and you don't want the overhead of creating a session for your thousands of visitors? aiya. It seems you have to do something like this: if (isset($_COOKIE[session_name()])) { $cookie_id = $_COOKIE[session_name()]; session_start(); if ($cookie_id == session_id()) { // ok - session start "resumed" .. did not create } else { // nope.. session_start() just created a new session - so terminate it // no session } } else { // no session } the first check simply tells you if the session cookie exists (it may not be a valid session id, and doesn't mean a session is in place (i.e. the session file may not exist)). So you've got to compare the session_id in the cookie with the session_id() after calling session_start(). Then you'll have to do subsequent checks (like checking session variables you would have set up when the admin signed in) to make sure the session is a valid one at your application level. Seriously - is it really this hard? Am I missing something?

« previous php.notes (#150245) next »