Ubuntu Server 11.04 installation memcache and PHP use Memcache to store the session method _php tips

Source: Internet
Author: User
Tags install php memcached memory usage session id php session php code php programming sessions

This example describes the Ubuntu server 11.04 installation memcache and the way PHP uses Memcache to store sessions. Share to everyone for your reference, specific as follows:

1, first install Memcache service end:

sudo apt-get install memcached

The system starts automatically after the installation completes the Memcached service consumes 11211 ports

If you need to reconfigure the 11211-port service, turn off the open memcached service

To start manually:

Memcached-d-M 128-p 11211-u memcache

Here you need to explain the startup parameters for the memcached service:

-P Listening Port
The IP address of the-l connection, the default is native
-D Start memcached service
-D Restart Restart memcached service
-D Stop|shutdown shut down the running memcached service
-D Install installation memcached service
-d Uninstall Uninstall memcached service
-U Run as (only valid when run as root)
-m maximum memory usage, in MB. Default 64MB
-Returns an error when M memory is exhausted instead of deleting the item
-C Maximum Simultaneous connection number, default is 1024
-F Block size growth factor, default is 1.25-n minimum allocation space, key+value+flags default is 48
-H Display Help

2. Install PHP Memecache Client

$ sudo apt-get install Php5-memcache

Restart the Web server

To test Memcache code:

<?php
$mem = new Memcache;//Create Memcache Object
$mem->connect ("127.0.0.1", 11211);//Connect Memcache server
$val = "It's a memcache test."
$key = MD5 ($val);
if ($k = $mem->get ($key)) {//To determine whether to obtain the specified key
  echo ' from cache: '. $k;
} else {
  echo ' normal '; Here we need to replace the query database and create the cache in actual use.
  $mem->set ($key, $val, 0, 120); Add a cache insertion, cache time of 120s
}

Storing session with Memcache

In general, the session is stored as a text file on the server side. If you use Seesion, or if the PHP file calls the session variable, you must start it before calling session and use the Session_Start () function. Other do not need you to set up, PHP automatically completes the session file creation. The default session path is the server's system Temp folder.

However, if you encounter a large amount of data sesstion, the use of file-based session access bottlenecks may be in the disk IO operation, now use memcached to save sessions data, directly through the memory of the way, the efficiency naturally can improve a lot. The speed of reading and writing is much faster than files, and it is easier to share sessions with multiple servers, and configuring these servers to use the same set of memcached servers can reduce the extra effort.

The disadvantage is that the session data is stored in the memory, and once the downtime, the data will be lost. But it is not a serious problem for the session data.

How to use memcached to store the session? The following are the basic configuration steps:

1. Install memcached (skip, unclear bobbin can view the previous article: http://www.jb51.net/article/85510.htm)
The "Registered save handlers" in the Phpinfo output will have the "Files User SQLite".

2. Modify the configuration file,

①. Global settings in php.ini (* requires reboot of server)

Session.save_handler = memcache
Session.save_path = "tcp://127.0.0.1:11211"

②. or a directory of. htaccess:

Php_value Session.save_handler "Memcache"
php_value session.save_path "tcp://127.0.0.1:11211"

③. can also be in one application:

Ini_set ("Session.save_handler", "memcache");
Ini_set ("Session.save_path", "tcp://127.0.0.1:11211");

Note: The use of multiple memcached servers is separated by commas "," and as described in the Memcache::addserver () document, you can take additional arguments "persistent", "weight", "timeout", "Retry" _interval "And so on, like this:

"Tcp://host:port?persistent=1&weight=2,tcp://host2:port2".

3. Start memcached

Copy Code code as follows:
Memcached-d-M 10-u root-l 127.0.0.1-p 11211-c 256-p/tmp/memcached.pid

4. Test Create a session

<?php
//set_session.php
session_start ();
if (!isset ($_session[' admin ')) {
  $_session[' admin ' = ' wan ';
}
Print $_session[' admin '];
print "/n";
Print session_id ();
? >

5. Check with SessionID to memcached

<?php
//get_session.php
$mem = new Memcache;
$mem->connect ("127.0.0.1", 11211);
Var_dump ($mem->get (' 0935216dbc0d721d629f89efb89affa6 '));
? >

Copy Code code as follows:
[Root@localhost html]#/usr/local/webserver/php/bin/php-f get_session.php

Output results:

String "Admin|s:3: Wan"; "

Prove that the session is working correctly.

Go deep into a multi-domain site again share session data with Memcache methods

By understanding the working principle of the session, we can find that by default, each server will have its own sessions ID for the same client separately, for example, for the same user browser, a server generates an ID that is 30DE1E9DE3192BA6CE2992D27A1B6A0A, while the B server generates C72665AF28A8B14C0FE11AFE3B59B51B. In addition, the PHP session data are stored separately in the file system of the server.

Once you have identified the problem, you can proceed to solve it. To share session data, you have to implement two goals: one is that each server must have the same session ID for the same client, and it can be passed through the same COOKIE, which means that each server must be able to read the same one named Phpsessid COOKIE, and the other is how the session data is stored/positioned to ensure that each server is accessible. Simply put, the session ID of a multiple-server shared client, and the server-side session data must also be shared.

The implementation of the first goal is actually very simple, only need to make a special setting for the domain of the cookie, by default, the domain of the cookie is the domain name/IP address of the current server, and if the domain is different, the cookies set by each server are not accessible to each other, such as www.aaa.com servers are cookies that cannot read and write to www.bbb.com server settings. Here we call the same Web server has its particularity, that is, they belong to the same level of domain, such as: Tieba.xiaoyuan.com and www.xiaoyuan.com belong to the domain. xiaoyuan.com, then we can set the domain of the COOKIE as. Xiaoyuan.com, so tieba.xiaoyuan.com, www.xiaoyuan.com, and so on can access this COOKIE. The Setup method in the PHP code is as follows:

<?php
ini_set (' Session.cookie_domain ', ' xiaoyuan.com ');
? >

The purpose of sharing the same client session ID for each server is achieved.

So you can a.domain.com under the

session.php

<?php
ini_set (' Session.cookie_domain ', ' domain.com ');
Session_Start ();
if (!isset ($_session[' admin ')) {
  $_session[' admin ' = ' wan ';
}
Print $_session[' admin '];
print "\ n";
Print session_id ();

Under the b.domain.com

session2.php

<?php
ini_set (' Session.cookie_domain ', ' domain.com ');
Session_Start ();
echo $_session[' admin '];

I hope this article will help you with your PHP programming on the Ubuntu platform.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.