码迷,mamicode.com
首页 > Web开发 > 详细

ThinkPHP5.0下,利用Cookie和Session来存储用户信息

时间:2018-11-04 11:20:51      阅读:422      评论:0      收藏:0      [点我收藏+]

标签:thinkphp5   clear   判断   传输   created   logout   利用   this   http   

利用tp5框架封装好的Cookie类和Session类。若发现过期时间没有生效,可以试试清除缓存。

登录页面Login.php

<?php
/**
* Created by PhpStorm.
* User: zjl
* Date: 2018/11/1
* Time: 15:21
*/
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class Login extends Controller{
public function index(){
return $this->fetch(‘index‘);
}
public function login()
{
$request = Request::instance();
//判断post过来的数据是否被提交过来
if($request->isPost()){
$data = $request->param();
//对提交的数据进行判断
if(empty($data[‘user‘]) || empty($data[‘password‘])){
exit(json_encode(array(‘status‘=>0,‘message‘=>‘用户名或密码不能为空‘)));
}
//对数据进行过滤
$username = addslashes(trim(stripslashes($data[‘user‘])));
$password = addslashes(trim(stripslashes($data[‘password‘])));
$config_session = [
‘prefix‘ => ‘admin‘, // session 名称前缀
‘expire‘ => 7200, // session 过期时间
‘use_trans_sid‘ => 1, //跨页传递
‘use_only_cookies‘ => 0, //是否只开启基于cookies的session的会话方式
];
$session = new Session();
$session->init($config_session);
$session->prefix();
$session->set(‘user‘,$username,‘admin‘);
$session->set(‘password‘,$password,‘admin‘);
$config_cookie = [
‘prefix‘ => ‘admin‘, // cookie 名称前缀
‘expire‘ => 1800, // cookie 保存时间
‘path‘ => ‘/‘, // cookie 保存路径
‘domain‘ => ‘‘, // cookie 有效域名
‘secure‘ => false, // cookie 启用安全传输
‘httponly‘ => false, // httponly 设置
‘setcookie‘ => true, // 是否使用 setcookie
];
$cookie = new Cookie();
$cookie->init($config_cookie);
$cookie->prefix();
$cookie->set("sessionId",session_id());
$this->redirect(‘/index.php/admin/Index/index‘);
}
}
}

主页面Index.php
<?php
/**
* Created by PhpStorm.
* User: zjl
* Date: 2018/11/1
* Time: 15:21
*/
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class Index extends Controller{
public function index(){
if(Cookie::has("sessionId",‘admin‘)){
if(Session::has(‘user‘,‘admin‘) && Session::has(‘password‘,‘admin‘)){
$user = Session::get(‘user‘,‘admin‘);
$password = Session::get(‘password‘,‘admin‘);
$this->assign(‘user‘,$user);
$this->assign(‘password‘,$password);
return $this->fetch(‘index‘);
}else{
//‘session过期了‘;
$this->redirect(‘/index.php/admin/Login/index‘);

}
}else{
//‘cookie过期了‘;
$this->redirect(‘/index.php/admin/Login/index‘);
}
}
public function logout()
{
Session::flush();
Cookie::clear(‘admin‘);
$this->redirect(‘admin/Login/index‘);

}
}

ThinkPHP5.0下,利用Cookie和Session来存储用户信息

标签:thinkphp5   clear   判断   传输   created   logout   利用   this   http   

原文地址:https://www.cnblogs.com/fish-minuet/p/9903068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!