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?

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

报告相同问题?

悬赏问题

  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误