利用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‘); }}
原文地址:https://www.cnblogs.com/fish-minuet/p/9903068.html
时间: 2024-10-29 19:11:52