douqie1884 2015-10-07 21:21
浏览 41
已采纳

取消设置会话然后返回其数据

I want to get a session and then return its data then unset it (or get a session and then unset it then return the data), I am doing 2 (header) redirects. after setting the session till getting the session.

but the problem is its not returning anything.

following is the class I am using:

class Session {

private $session_data1;


public function __construct() {

    session_start();  // starts session on all files at first...
}



public function set_session($session_name, $session_data) {

    return ($_SESSION[$session_name] = $session_data) ? true : false;
}


public function get_session($session_name) {

    return isset($_SESSION[$session_name]) ? $_SESSION[$session_name] : false;
}



public function get_session_once($session_name) {

    $this->session_data1 = $this->get_session($session_name);

    $this->unset_session($session_name);

    return $this->session_data1;
}



public function unset_session($session_name) {

    if (isset($_SESSION[$session_name])) {

        unset($_SESSION[$session_name]);
        // return true;
    }
}



public function destroy_all_session() {

    session_destroy();
}

}

$session = new Session();

I am using 'set_session()' to set a session and wanted to use 'get_session_once()' which will unset the session and then return the value of that session.

if I dont unset it in the method 'get_session_once()' then it works, like the following:

public function get_session_once($session_name) {

    $this->session_data1 = $this->get_session($session_name);

    // $this->unset_session($session_name);

    return $this->session_data1;
}

I am new in PHP, please help

  • 写回答

1条回答 默认 最新

  • douqian3712 2015-10-07 21:46
    关注

    I tested this, and for me it's working.

    <?
    
        $session = new Session();
    
        $session->set_session('Username', 'StackOverflow');
    
        echo $session->get_session_once('Username'); // echos 'StackOverflow'
    
        echo $session->get_session_once('Username'); // no echo
    
    ?>
    

    This is still the same:

    public function get_session_once($session_name) {
    
        $this->session_data1 = $this->get_session($session_name);
    
        $this->unset_session($session_name);
    
        return $this->session_data1;
    }
    

    Maybe the header redirect is the cause, it might be clear/delete the session.

    Did you put session_start() at the start of every page?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源