我应该如何在PHP中实现延迟会话创建?

时间:2010-06-08 14:22:40

标签: php session

默认情况下,即使会话中没有数据,PHP的会话处理机制也会设置会话cookie标头并存储会话。如果会话中没有设置数据,那么我不希望在响应中向客户端发送Set-Cookie标头,并且我不希望在服务器上存储空会话记录。如果数据已添加到$_SESSION,则应继续正常行为。

我的目标是实现Drupal 7和Pressflow排序的延迟会话创建行为,其中没有存储会话(或发送会话cookie标头),除非在应用程序期间将数据添加到$_SESSION数组执行。这种行为的关键是允许反向代理(如Varnish)缓存并提供匿名流量,同时让经过身份验证的请求传递给Apache / PHP。 Varnish(或其他代理服务器)配置为在没有cookie的情况下传递任何请求,假设存在cookie,那么请求是针对特定客户端的。

我已使用session_set_save_handler()移植了来自Pressflow的会话处理代码并覆盖了session_write()的实现,以便在保存之前检查$_SESSION数组中的数据,并将其写为库如果这是最佳/唯一的路线,请在此处添加答案。

我的问题:虽然我可以实现一个完全自定义的session_set_save_handler()系统,但是有一种更简单的方法来以相对通用的方式获得这种懒惰的会话创建行为对大多数应用程序透明

4 个答案:

答案 0 :(得分:6)

好吧,一个选项是使用会话类来启动/停止/存储会话中的数据。所以,你可以这样做:

class Session implements ArrayAccess {
    protected $closed = false;
    protected $data = array();
    protected $name = 'mySessionName';
    protected $started = false;

    protected function __construct() {
        if (isset($_COOKIE[$this->name])) $this->start();
        $this->data = $_SESSION;
    }

    public static function initialize() {
        if (is_object($_SESSION)) return $_SESSION;
        $_SESSION = new Session();
        register_shutdown_function(array($_SESSION, 'close'));
        return $_SESSION;
    }

    public function close() {
        if ($this->closed) return false;
        if (!$this->started) {
            $_SESSION = array();
        } else {
            $_SESSION = $this->data;
        }
        session_write_close();
        $this->started = false;
        $this->closed = true;
    }

    public function offsetExists($offset) { 
        return isset($this->data[$offset]); 
    }

    public function offsetGet($offset) {
        if (!isset($this->data[$offset])) {
            throw new OutOfBoundsException('Key does not exist');
        }
        return $this->data[$offset]; 
    }

    public function offsetSet($offset, $value) {
        $this->set($offset, $value);
    }

    public function offsetUnset($offset) {
        if (isset($this->data[$offset])) unset($this->data[$offset]);
    }

    public function set($key, $value) {
        if (!$this->started) $this->start();
        $this->data[$key] = $value;
    }

    public function start() {
        session_name($this->name);
        session_start();
        $this->started = true;
    }
}

要在脚本调用开始时使用Session::initialize()。它将用对象替换$ _SESSION,并设置延迟加载。之后,你可以做到

$_SESSION['user_id'] = 1;

如果会话未启动,则会是,并且user_id键将设置为1.如果您想要关闭(提交)会话,请致电$_SESSION->close()

您可能希望添加更多会话管理功能(例如destroy,regenerate_id,更改会话名称等功能),但这应该实现您之后的基本功能...... < / p>

它不是一个save_handler,它只是一个管理你的会话的类。如果你真的想要,你可以在类中实现ArrayAccess,并在构造中用该类替换$ _SESSION(这样做的好处是,遗留代码仍然可以像以前一样使用session而不调用$session->setData() )。唯一的缺点是我不确定PHP使用的序列化例程是否可以正常工作(你需要在某个时候将数组放回$ _SESSION ......可能是register_shutdown_function() ...

答案 1 :(得分:3)

我已经针对此问题开发了working solution,该问题使用session_set_save_handler()和一组自定义会话存储方法,用于在写出会话数据之前检查$_SESSION数组中的内容。如果没有要为会话写入的数据,则使用header('Set-Cookie:', true);来阻止在响应中发送PHP的会话cookie。

此代码的最新版本以及文档和示例均为available on GitHub。在下面的代码中,使这项工作的重要功能是lazysess_read($id)lazysess_write($id, $sess_data)

<?php
/**
 * This file registers session save handlers so that sessions are not created if no data
 * has been added to the $_SESSION array.
 * 
 * This code is based on the session handling code in Pressflow (a backport of
 * Drupal 7 performance features to Drupal 6) as well as the example code described
 * the PHP.net documentation for session_set_save_handler(). The actual session data
 * storage in the file-system is directly from the PHP.net example while the switching
 * based on session data presence is merged in from Pressflow's includes/session.inc
 *
 * Links:
 *      http://www.php.net/manual/en/function.session-set-save-handler.php
 *      http://bazaar.launchpad.net/~pressflow/pressflow/6/annotate/head:/includes/session.inc
 *
 * Caveats:
 *      - Requires output buffering before session_write_close(). If content is 
 *        sent before shutdown or session_write_close() is called manually, then 
 *        the check for an empty session won't happen and Set-Cookie headers will
 *        get sent.
 *        
 *        Work-around: Call session_write_close() before using flush();
 *        
 *      - The current implementation blows away all Set-Cookie headers if the
 *        session is empty. This basic implementation will prevent any additional
 *        cookie use and should be improved if using non-session cookies.
 *
 * @copyright Copyright &copy; 2010, Middlebury College
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License (GPL), Version 3 or later.
 */ 

/*********************************************************
 * Storage Callbacks
 *********************************************************/

function lazysess_open($save_path, $session_name)
{
    global $sess_save_path;

    $sess_save_path = $save_path;
    return(true);
}

function lazysess_close()
{
    return(true);
}

function lazysess_read($id)
{ 
    // Write and Close handlers are called after destructing objects
    // since PHP 5.0.5.
    // Thus destructors can use sessions but session handler can't use objects.
    // So we are moving session closure before destructing objects.
    register_shutdown_function('session_write_close');

    // Handle the case of first time visitors and clients that don't store cookies (eg. web crawlers).
    if (!isset($_COOKIE[session_name()])) {
        return '';
    }

    // Continue with reading.
    global $sess_save_path;

    $sess_file = "$sess_save_path/sess_$id";
    return (string) @file_get_contents($sess_file);
}

function lazysess_write($id, $sess_data)
{ 
    // If saving of session data is disabled, or if a new empty anonymous session
    // has been started, do nothing. This keeps anonymous users, including
    // crawlers, out of the session table, unless they actually have something
    // stored in $_SESSION.
    if (empty($_COOKIE[session_name()]) && empty($sess_data)) {

        // Ensure that the client doesn't store the session cookie as it is worthless
        lazysess_remove_session_cookie_header();

        return TRUE;
    }

    // Continue with storage
    global $sess_save_path;

    $sess_file = "$sess_save_path/sess_$id";
    if ($fp = @fopen($sess_file, "w")) {
        $return = fwrite($fp, $sess_data);
        fclose($fp);
        return $return;
    } else {
        return(false);
    }

}

function lazysess_destroy($id)
{
    // If the session ID being destroyed is the one of the current user,
    // clean-up his/her session data and cookie.
    if ($id == session_id()) {
        global $user;

        // Reset $_SESSION and $user to prevent a new session from being started
        // in drupal_session_commit()
        $_SESSION = array();

        // Unset the session cookie.
        lazysess_set_delete_cookie_header();
        if (isset($_COOKIE[session_name()])) {
            unset($_COOKIE[session_name()]);
        }
    }


    // Continue with destruction
    global $sess_save_path;

    $sess_file = "$sess_save_path/sess_$id";
    return(@unlink($sess_file));
}

function lazysess_gc($maxlifetime)
{
    global $sess_save_path;

    foreach (glob("$sess_save_path/sess_*") as $filename) {
        if (filemtime($filename) + $maxlifetime < time()) {
            @unlink($filename);
        }
    }
    return true;
}

/*********************************************************
 * Helper functions
 *********************************************************/

function lazysess_set_delete_cookie_header() {
    $params = session_get_cookie_params();

    if (version_compare(PHP_VERSION, '5.2.0') === 1) {
        setcookie(session_name(), '', $_SERVER['REQUEST_TIME'] - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
    }
    else {
        setcookie(session_name(), '', $_SERVER['REQUEST_TIME'] - 3600, $params['path'], $params['domain'], $params['secure']);          
    }
}

function lazysess_remove_session_cookie_header () {
    // Note: this implementation will blow away all Set-Cookie headers, not just
    // those for the session cookie. If your app uses other cookies, reimplement
    // this function.
    header('Set-Cookie:', true);
}

/*********************************************************
 * Register the save handlers
 *********************************************************/

session_set_save_handler('lazysess_open', 'lazysess_close', 'lazysess_read', 'lazysess_write', 'lazysess_destroy', 'lazysess_gc');

虽然这个解决方案有效并且对包括它在内的应用程序大多是透明的,但它需要重写整个会话存储机制,而不是依靠内置的存储机制和交换机来保存与否。

答案 2 :(得分:0)

我在这里创建了一个懒惰的会话证明:

  • 它使用本机php会话处理程序和_SESSION数组
  • 只有在发送了cookie或
  • 后才启动会话
  • 如果添加了$ _SESSION数组
  • ,它会启动会话
  • 如果会话已启动且$ _SESSION为空,则会删除会话

将在接下来的几天内扩展它:

https://github.com/s0enke/php-lazy-session

答案 3 :(得分:0)

这个主题正在讨论未来的php版本 https://wiki.php.net/rfc/session-read_only-lazy_write