020.CI4框架CodeIgniter, 关于session的创建,删除和读取

01.在BaseController.php中添加一下代码,如图所示

$this->session = \Config\Services::session();

 

 

02.在Home.php文件中,写入session的创建如下代码:

<?php namespace App\Controllers;

class Home extends BaseController
{

    function __construct()
    {

    }

    // http://127.0.0.1/CI4/public/index.php/home/getsession
    //设置session
    public function setsession()
    {
        //设置session
        $data = array(
            'username' => '田攀',
            'password' => '青青子衿悠悠我心',
        );
        $this->session->set($data);

        // 有效性只有5秒
        $this->session->setTempdata('user', '张三', 5);
    }

    //删除session
    public function removesession()
    {
        //输出session
        $this->session->remove('username');
    }

    //取session子
    public function getsession()
    {
        //输出session
        ShowMessage($this->session->username);
        //输出session
        ShowMessage($this->session->getTempdata('user'));
        //输出没有的session
        ShowMessage($this->session->user);
        //判断是否有session
        ShowMessage($this->session->has('user'));
        //判断是否有session
        ShowMessage($this->session->has('username'));
    }
}

 

 

3. 我们打开浏览器,访问http://127.0.0.1/CI4/public/index.php/home/setsession,用来设置session

 

 

4.我们访问http://127.0.0.1/CI4/public/index.php/home/getsession,用来读取session

 

 

5.我们过5秒之后,再访问http://127.0.0.1/CI4/public/index.php/home/getsession,用来读取session

 

 

6.我们访问http://127.0.0.1/CI4/public/index.php/home/removesession,用来删除session

7.我们再访问http://127.0.0.1/CI4/public/index.php/home/getsession,用来读取session

 

 

知识有价,如果您认为这篇文章有价值,认同作者的付出,可以微信二维码打赏任意金额给作者(微信号:382477247)哦,谢谢。

posted @ 2020-02-28 22:20  像一棵海草海草海草  阅读(843)  评论(0编辑  收藏  举报