Home  >  Article  >  Backend Development  >  memcache 储存 php session

memcache 储存 php session

WBOY
WBOYOriginal
2016-06-13 13:06:53670browse

memcache 存储 php session

1. 修改配置文件,在 php.ini 中全局设置:

session.save_handler = memcache
session.save_path = "tcp://127.0.0.1:11211"
或者某个目录下的 .htaccess :
php_value session.save_handler "memcache"
php_value session.save_path  "tcp://127.0.0.1:11211"
再或者在某个一个应用中:
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://127.0.0.1:11211");?

使用多个 memcached server 时用逗号","隔开,并且和 Memcache::addServer() 文档中说明的一样,可以带额外的参数"persistent"、"weight"、"timeout"、"retry_interval" 等等,类似这样的:"tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2" 。


5. 在程序中使用 memcache 来作 session 存储,用例子测试一下:

<?php ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://127.0.0.1:11211");
session_start();
if($_GET['a']){
 $_SESSION['joo'] = 'hello~';
}else{
 print_r($_SESSION);
}
$memcache_obj = new Memcache;
$memcache_obj->connect('127.0.0.1', 11211);
$var = $memcache_obj->get(session_id());
echo $var;
?>
会有看到
Array ( [joo] => hello~ ) joo|s:6:"hello~";

这样的输出,证明 session 正常工作。

用 memcache 来存储 session 在读写速度上会比 files 时快很多,而且在多个服务器需要共用 session 时会比较方便,将这些服务器都配置成使用同一组 memcached 服务器就可以,减少了额外的工作量。
缺点是 session 数据都保存在 memory 中,持久化方面有所欠缺,但对 session 数据来说也不是很大的问题。

1 楼 jimmyyem 2012-02-15  
我实在win下面测试的,我安装了memcache,不是memcached,请问我在php.ini和程序里改  2种都试过了,发现还不行
指点一下
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