如何在不调用session_start的情况下获取会话

时间:2011-04-21 19:04:52

标签: php class session comet

我现在有一个彗星页面,如果我在顶部调用session_start然后会话冻结,我的解决办法就是:

function getTables($sessionID = null){

        if(!isset($this->output)){
            $this->output = array();
        }

        if(!isset($this->output[$this->sessID])){
            $this->output[$this->sessID] = array();
        }
        $hostname = php_uname("n");

        $sess_ini = session_save_path();
        chdir($sess_ini);
        if(false === ($save = @file_get_contents("sess_$this->sessID"))){
            $cwd = getcwd();
            chdir($this->location);
            return (isset($this->returnJSON[$this->sessID])?$this->returnJSON[$this->sessID]
                    :json_encode(array(
                        'sess_local'=>"$sess_ini/sess_$this->sessID",
                        'save'=>$save,
                        'hostname'=>$hostname,
                        'cwd'=>$cwd,
                        'reg_local'=>$this->location,
                        )
                    )
                );
        }
        chdir($this->location);
        //session_id($sessionID);
        $sessions = explode("|",$save);
        $_SESSION['all'] = array();
        foreach($sessions as $key=>$sess){
            if(trim($sess)=='all' && isset($sessions[$key+1])){
                $_SESSION['all'] = unserialize(trim(urldecode($sessions[$key+1])));
                break;
            }
        }
        ...

我是否有更好的方法来获取进入会话文件的会话变量?

2 个答案:

答案 0 :(得分:3)

你的工作可以简单得多:

 <?php
 //yes, start normally.
 session_start();

 //now, immediately harvest the variables you need to remember from the $_SESSION
 $somevar_you_want_to_remember = $_SESSION['somevar'];

 //close the session, so it won't lock:
 session_write_close();

 //disable some errors which aren't really errors:
 ini_set('session.use_cookies',false);
 session_cache_limiter(false);

 //you are now free to do anything you like:
 while(true){

     echo "<script>window.parent.test_function('".time().' sessionvar: '.$somevar_you_want_to_remember."');</script>";

     flush_buffers();
     sleep(1);
     //if you need to refresh your variable, you can just reopen the session:
     session_start();
     $somevar_you_want_to_remember = $_SESSION['somevar'];
     //and immediately close again
     session_write_close();         
}

您可以编写一些辅助函数,例如:

 function SaveQuickSessionVar($name,$value){
      session_start();
      $_SESSION[$name] = $value;
     session_write_close();     
 }

 function GetQuickSessionVar($name){
     session_start();
     $var = $_SESSION[$name];
     session_write_close(); 
     return $var;    
 }

答案 1 :(得分:3)

PHP的默认会话处理程序在会话文件被脚本使用时锁定会话文件。 Comet使处理程序脚本长时间处于活动状态,这会使会话锁定。你可以通过

来解决它
session_start();
session_write_close();
在你的Comet脚本中

。它将使用存储的数据填充$ _SESSION,然后关闭会话文件并放弃对它的锁定。 $ _SESSION中的数据仍然存在且可用,您甚至可以更改它。唯一的区别是,除非您在脚本中执行后续session_start(),否则这些更改将不会写入磁盘会话文件。

因此,您可以在脚本中使用常规PHP会话,只需要注意任何长时间运行的部分在该部分开始执行之前关闭会话。