php session to redis

2022-10-11 21:49:21 148 0
魁首哥

之前面试的时候,经常问别人, SESSION , COOKIE 是什么,怎么存储的?

有一个人给我胡说了半天,说session的所有信息都通存在http的 header 里面,说着说着,又变成了存在http body里面。。。

php session to redis

好,今天谈谈这个。

我们看到php的session.name初始值是”PHPSESSID”。

The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value.

session name 存储的值,就是session id,即:

COOKIE(PHPSESSID) = SESSION ID

我们保存用户登录信息,一般保存在SESSION里面,默认的SESSION是使用PHP内部文件的存储的:

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

当我们多级部署时,必须使用其他方式存储session,一般存储在db,cache中,举个 redis session的例子:

class RedisSessionCache /*implements HandlerInterface */{

protected $redis;

public function __construct($redis) {

$this->redis = $redis;

@session_set_save_handler(array($this,’open’),array($this,’ close ‘),array($this,’read’),array($this,’write’),array($this,’

destroy’),array($this,’gc’));

}

public function close() {

return true;

}

public function gc ( int $maxlifetime ) {

return true;

}

public function open ( $save_path, $_name ) {

return true;

}

public function read ( $_id ) {

$data = $this->redis->get($_id);

return $data === false ? ” : $data;

}

public function write ( $_id , $_data ) {

$this->redis->set($_id, $_data);

}

public function destroy( $_id ) {

$this->redis->delete($_id);

}

}

$redis = new Redis();

$redis->connect(‘localhost’, ‘6379’);

$redis->auth(‘test123’);

$session = new RedisSessionCache($redis);

session_start();

$_SESSION[‘test’.$_SERVER[‘REMOTE_ADDR’]]=123;

var_dump($_SESSION);

访问之后,我们看到COOKIE PHPSESSID 的值是 qm921l9jtm9nvq1g6ijisbon91 ,连接redis获取该值:

telnet 127.0.0.1 6379Trying 127.0.0.1…

Connected to 127.0.0.1.

Escape character is ‘^]’.

auth test123

+OK

get qm921l9jtm9nvq1g6ijisbon91$24test192.168.235.1|i:123;

这样就把session保存在redis中了,一个问题,怎么设置session name 的COOKIE过期时间呢?

session_set_cookie_params Set the session cookie parameters .

收藏
分享
海报
0 条评论
148
上一篇:深入理解php static变量、方法 static后期静态绑定 下一篇:PHP之常用的RBAC权限管理详解

本站已关闭游客评论,请登录或者注册后再评论吧~

忘记密码?

图形验证码