Is it possible to check if a certain session ID exists without starting a new one?
The reasons I'm asking this are:
If every user not logged in visiting the site requires
session_start()
, soon the session folder will be bloated with unnecessary files (even with garbage collector cleaning up expired sessions).
Of course this can be mitigated by destroying the sessions of such users. However, in this case, it seems there would be an overhead of creating and destroying files (unless PHP is smart enough to cancel these operations). Is this a bad practice?If the user is just a guest and doesn't require a session, there is no need to create one for him.
Ideal Solutions:
if( session_exist($_COOKIE['PHPSESSID']) )
{
session_start();
}
Or:
session_start(RESUME_ONLY);
Follow-up
There is a PHP package that explains much better the aforementioned issue. Briefly, some interesting excerpts are:
Resuming A Session
[...]
You could start a new session yourself to repopulate$_SESSION
, but that will incur a performance overhead if you don't actually need the session data. Similarly, there may be no need to start a session when there was no session previously (and thus no data to repopulate into$_SESSION
). What we need is a way to start a session if one was started previously, but avoid starting a session if none was started previously.
[...]
If the cookie is not present, it will not start a session, and return to the calling code. This avoids starting a session when there is no$_SESSION
data to be populated.
Source: Aura.Auth
Notes:
This question was initially posted as Checking for PHP session without starting one?.
However, IMO, none of the answers addressed properly the issue.