PhpSession can be saved to text, memory, and database. Today we are talking about how to save it to Redis.
Php sessions can be stored in text, memory, and databases. Today we are talking about how to store them in Redis.
Of course, you must first install php extensions. For details, refer to this article: Redis and PHP extension installation.
Modify php. ini settings
The Code is as follows:
Session. save_handler = redis
Session. save_path = "tcp: // 127.0.0.1: 6379 ″
Restart php-fpm, nginx, and phpinfo () after modification ()
Session redis
If you do not want to modify php. ini
The Code is as follows:
Ini_set ("session. save_handler", "redis ");
Ini_set ("session. save_path", "tcp: // 127.0.0.1: 6379 ″);
If the connection password requirepass is set in the configuration file/etc/redis. conf to save the session, an error will be reported. In save_path, write tcp: // 127.0.0.1: 6379? Auth = authpwd.
Some netizens mentioned that the session value stored in redis or memcache has the concurrency consistency problem, which has not been carefully tested.
The Code is as follows:
// Remove the comments of the following two lines If php. ini is not modified
// Ini_set ('session. save_handler', 'redis ');
// Ini_set ('session. save_path ', 'tcp: // 127.0.0.1: 6379 ');
Session_start ();
$ _ SESSION ['sessionid'] = 'this is session content! ';
Echo $ _ SESSION ['sessionid'];
Echo'
';
$ Redis = new redis ();
$ Redis-> connect ('2017. 0.0.1 ', 127 );
// Redis uses session_id as the key and stores it as a string
Echo $ redis-> get ('phpredis _ SESSION: '. session_id ());
?>