Categories


Archives


Recent Posts


Categories


Non-Deterministic PHP Session Saving in Magento

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

I gave this little bit of Magento code an ugh on Twitter.

#File: app/code/core/Mage/Core/Model/Resource/Session.php
public function __destruct()
{
    session_write_close();
}

Why? Because PHP automatically calls __destruct when it cleans up memory for an object, which means this code could potentially close and save the session before the PHP request finishes. This, in turn, could make sessions appear broken to a client programmer.

Now, this doesn’t happen with a stock Magento because Magento core code instantiates the session resource as a Magento singleton

Mage::getResourceSingleton('core/session');

Magento’s singleton implementation keeps a reference to the object around for the entire request, so PHP never calls __destruct.

However, if you instantiate the resource model as a regular model (because you wanted to reuse the “read/write sessions from database” code), you’ve created a potential bug if PHP garbage collects your model instance.

The solution, of course, is don’t do that, but relying on PHP’s __destruct method for something other than memory cleanup in an object that’s not guaranteed to stay a singleton seems sketchy at best, and destined to cause problems for developers who need to make customizations to session storage.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 18th March 2014

email hidden; JavaScript is required