Improve PHP Performance by Limiting Session Cookies
Letâs start with the assumption that on many web sites, a small percentage of web traffic is actually from visitors who are logged in. In other words, many visitors arrive at your site, look at a page or two, maybe search for products or content, and then leave. Why bother setting a session for all of these page views if your not storing anything in it?
What happens when a PHP session starts up? A cookie is set for the visitorâs browser with the session identifier, âPHPSESSIDâ, by default. The session data, if available, is loaded from the session store, which is in a file â unless youâve moved it to something faster. The data that is loaded is then unserialized into parameters in the $_SESSION global.
Additionally, at startup the PHP session handler rolls the dice to see if itâs time to do garbage collection on expired sessions. Unless youâve changed the default settings for PHP, then thereâs a 1% chance that PHP will have to sort through all of your available session files to find out if any are ripe for dismissal.
This is just a summary. Iâll readily admit I donât know all of the internals of session management in PHP. I also canât speak to whether PHP re-saves your visitorâs session on every page view, whether or not the data has been changed. If anyone can answer that, Iâd love to know.
Finally, that once you have a PHP session running, some additional cache-busting HTTP headers seem to be added to the server response for a page view:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
These headers make it impossible for your browser to cache a page, even if itâs a PHP script that returns virtually static content.
if (isset($_COOKIE['PHPSESSID'])) {
session_start();
}
This code could go in one of two places, either in the constructor for a login class, or if you potentially need session data in more places in your code, maybe in a file that gets auto-loaded on every request.
Once you get to a sign-in page, the login class would be responsible for firing up the session if it does not yet exist. For me, this is in a method called âauthenticate()â:
public function authenticate ()
{
if (!isset($_SESSION)) {
session_start();
}
// Do rest of user validation...
}
Note that we can use isset() to see if $_SESSION exists, which prevents E_NOTICE messages from being fired by session_start() if there is already a session in progress.
With these small changes, can surf all over site without having a session started up. The session is only initialized when I log into my siteâs account. Furthermore, you could add the additional behavior of explicitly deleting the session cookie for the visitor once they have logged-out of your site. While session_destroy() will delete data within the session file, it doesnât delete the cookie from your visitorâs browser.