title: How should I implement lazy session creation in PHP?
body: <p>By default, PHP's session handling mechanisms set a session cookie header and store a session even if there is no data in the session. If no data is set in the session then I don't want a <code>Set-Cookie</code> header sent to the client in the response and I don't want an empty session record stored on the server. If data is added to <code>$_SESSION</code>, then the normal behavior should continue.</p>
  
  <p>My goal is to implement lazy session creation behavior of the sort that Drupal 7 and <a href="https://launchpad.net/pressflow" rel="nofollow noreferrer">Pressflow</a> where no session is stored (or session cookie header sent) unless data is added to the <code>$_SESSION</code> array during application execution. The point of this behavior is to allow reverse proxies such as <a href="http://varnish-cache.org/" rel="nofollow noreferrer">Varnish</a> to cache and serve anonymous traffic while letting authenticated requests pass through to Apache/PHP. Varnish (or another proxy-server) is configured to pass through any requests without cookies, assuming correctly that if a cookie exists then the request is for a particular client.</p>
  
  <p>I have ported the session handling code from Pressflow that uses <code>session_set_save_handler()</code> and overrides the implementation of <code>session_write()</code> to check for data in the <code>$_SESSION</code> array before saving and will write this up as library and add an answer here if this is the best/only route to take.</p>
  
  <p><strong>My Question:</strong> While I can implement a fully custom <code>session_set_save_handler()</code> system, is there an easier way to get this lazy session creation behavior in a relatively generic way that would be <strong>transparent</strong> to most applications?</p>