Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for PHP session without starting one?

Is it possible to check for a session with out starting one?

The reason that I ask is, the app I am developing has an integrated admin interface. So when an admin is logged in they browse the same pages as the users to make their edits. Fields and options are shown based on the users privs.

This is causing two problems.

One is Because a session is being started, I can not enable browser caching features as the headers being sent are always:

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0       

I am using smarty to output the templates, and can't implement the:

$smarty->cache_modified_check = true;

to send a 304 not modified because a session has already been started. Using the above smarty param would be the perfect solution to browser caching for me.

Two is because every person using the site is starting a session the session directory gets filled with unneeded sessions.

I could just destroy the session if the user is not logged in, but then every single page load, the user would be creating and deleting a session. Is that bad practice?

So if I could just check to see if an active session exists without starting one all my problems would be solved. Any ideas? Doesn't the browser send the session cookie when requesting the page?

Something Ideally like this:

if (session_exists) {
 session_start();
 $users->priv = $_SESSION['priv'];
}
else {
 $users->priv = guest;
}

--------------- In response to Tony Miller ---------------

When using session_id(), you have to already have a session started for it to return an id.

session_start();
echo session_id($_SESSION);

or you can set an id for the session before calling session start

session_id("adfasdf");
session_start();
echo session_id($_SESSION);

//prints "adfasdf"

Neither of these help me. Unless I am missing something.

like image 789
user73119 Avatar asked Nov 23 '09 01:11

user73119


1 Answers

You'd be wanting session_id(), which returns empty string if no session is defined.

The documentation indicates that empty string (which is not "nothing") is returned if no session is started.

As the 2014 comments indicate (I wrote this answer in 2009), there is the possibility that a session could start if there is a cookie with a session id stored in it that could be picked up by session_start().

As of PHP 5.4.0, we now have session_status() but this didn't exist in 2009.

like image 69
Tony Miller Avatar answered Oct 14 '22 03:10

Tony Miller