Home  >  Article  >  Backend Development  >  How to implement Session with Redis in PHP distributed system

How to implement Session with Redis in PHP distributed system

小云云
小云云Original
2017-12-14 13:47:352178browse

This article mainly introduces the method of implementing Session in Redis in PHP distribution. The article introduces the use of the two methods in detail, and gives the sample code for testing. Friends in need can refer to it. I hope it can help everyone.

This article introduces the method of implementing Session in Redis in PHP distribution. Without further ado, let’s look at the two methods first.

Method 1:

Find the configuration file php.ini, modify it to the following content, save and restart the service


session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"


##Method 2:

Add the following content directly to the code:


ini_set("session.save_handler", "redis");
ini_set("session.save_path", "tcp://127.0.0.1:6379");


Note: If the connection password requirepass is set in the configuration file redis.conf, save_path needs to be written like thistcp://127.0.0.1:6379?auth=authpwd, otherwise an error will be reported when saving the session.

Test:

##

<?php
//ini_set("session.save_handler", "redis");
//ini_set("session.save_path", "tcp://127.0.0.1:6379");

session_start();

//存入session
$_SESSION[&#39;class&#39;] = array(&#39;name&#39; => &#39;toefl&#39;, &#39;num&#39; => 8);

//连接redis
$redis = new redis();
$redis->connect(&#39;127.0.0.1&#39;, 6379);

//检查session_id
echo &#39;session_id:&#39; . session_id() . &#39;<br/>&#39;;

//redis存入的session(redis用session_id作为key,以string的形式存储)
echo &#39;redis_session:&#39; . $redis->get(&#39;PHPREDIS_SESSION:&#39; . session_id()) . &#39;<br/>&#39;;

//php获取session值
echo &#39;php_session:&#39; . json_encode($_SESSION[&#39;class&#39;]);

Related recommendations:

Distributed Using Redis to implement session sharing

nginx+tomcat+redis to implement session sharing

Redis optimization experience summary

The above is the detailed content of How to implement Session with Redis in PHP distributed system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn