2010-06-08 67 views
13

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

我的目标是实现的Drupal 7和Pressflow其中没有会话被存储(或会话cookie头中发送)之类的懒惰会话创建行为除非数据被添加到应用程序执行期间的$_SESSION阵列。此行为的目的是允许反向代理(例如Varnish)缓存和提供匿名流量,同时让已认证的请求通过Apache/PHP。 Varnish(或其他代理服务器)被配置为在没有cookie的情况下通过任何请求,假设如果存在cookie,则该请求适用于特定客户端。

我已经从使用session_set_save_handler()和覆盖的session_write()执行保存前请检查$_SESSION阵列中的数据,并会在这里把这件事写成库,并添加一个答案,如果这是最好的Pressflow移植的会话处理代码/只有路线采取。

我的问题:虽然我可以实现完全定制session_set_save_handler()系统,有更简单的方式在一个相对通用的办法,这将是透明于大多数应用程序得到这个懒惰的会话创建的行为吗?

+0

@cletus:他说他的理由:*此行为的关键是允许像Varnish这样的反向代理缓存并提供匿名流量,同时让认证请求通过Apache/PHP。* – webbiedave 2010-06-08 14:33:15

+0

相关答案:[PHP Session类与CodeIgniter会话类类似?](http://stackoverflow.com/questions/ 11596082/php-session-class-similar-codeigniter-session-class/11596538#11596538) – hakre 2012-08-01 08:21:30

回答

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'); 

虽然这种解决方案可行,几乎都是透明的应用程序,包括它,它需要重写整个会话存储机制,而不是依赖于内置的存储机制与交换机保存或不。

+0

注意:由于这个lib完全不使用锁,因此并发请求可能会覆盖对方的内容。 – staabm 2014-09-30 08:32:02

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,更改会话名称的能力等),但是这应该实现您之后的基本功能......

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

+0

这仍然是最值得推荐的解决方案吗?我发现懒惰的会议很少,这让我觉得他是另一种解决方案。 – 2012-02-29 20:28:23

+0

不要将其他内容分配给'$ _SESSION'超全局。 PHP负责处理该变量,并且如果会话状态更改该变量get的set/unset/lost,甚至将PHP变为涅ana。就像你不应该做'$ _SESSION = array()'你不应该做'$ _SESSION = new XYZ()'。相反,通过类。 – hakre 2012-08-01 08:23:56

+0

而不是'new Session()'使用'new self()',你可以将类重命名为 – staabm 2014-10-14 15:56:34

0

我创造的概念在这里慵懒的会议证明:

  • 它采用了原生的PHP会话处理程序,并_SESSION阵列
  • 如果一个cookie被发送或
  • 它开始它只是启动会议会话如果事情已经加入了$ _SESSION阵列
  • ,如果一个会话开始和$ _SESSION是空删除会话

将在未来几天进行扩展:

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