Using Memcache in PHP

Source: Internet
Author: User
Tags add array file info connect sql string version iptables
\First, install the memcache extension
       First, let's check if our current PHP environment supports memcache extension through phpinfo () function. Create a new file info.php in the root directory of the server and write in the file.

<? php
    phpinfo ();

          

      Then enter http: //localhost/info.php in your browser to access, and then find out if there is a memcache extension. Generally, our server does not have the memcache extension installed by default, so we still have to install it ourselves. We first download the php_memcache.dll file from the Internet, and copy the file to the php extension directory (mine is php5 / ext /). Adding this file to the extension directory has not been completed. We need to configure the php.ini file in php Add extension = php_memcache.dll to the file, the php environment will automatically find the php extension directory and add this extension to the php environment. At this time, we restart apache and then visit http: //localhost/info.php to see

memcache.png This shows that our memcache extension is installed! We look at the php manual again and find that there are two ways to use the memcache extension, the first is a process-oriented use, and the other is an object-oriented use, and we generally use the object-oriented way.

    Second, the use of memcache
            Paste the code directly!

<? php
    // Instantiate the memcache class
    $ mem = new Memcache;
     
    // connect memcache server (parameters are server IP, port), pconnect--represents continuous connection
    $ mem-> connect ('localhost', 11211);
     
    // addserver means add memcache server, multiple memcache servers can implement distributed cache
    //$mem->addsever('www.pccxin.com ', 11211);
    //$mem->addsever('www.frontu.net ', 11211);
     
    // Add elements to the memcache server
    // bool Memcache :: add (string $ key, mixed $ var [, int $ flag [, int $ expire]])
    // The parameters are the key name, value (string | array | object), use the MEMCACHE_COMPRESSED tag to compress the data (using zlib), save time (in seconds)
    $ mem-> add ('mystr', 'This is my first memcache test!', MEMCACHE_COMPRESSED, 3600);
     
    // $ mem-> add ('mystr', 'This is my first memcache test!', MEMCACHE_COMPRESSED, 3600); // add will not be added repeatedly. If you want to change the value, use replace (), or set
 
    $ mem-> set ('mystr', 'This is my second memcache test!', MEMCACHE_COMPRESSED, 3600); // Save data to the server
     
    // delete an element from the server
    // $ mem-> delete ('mystr');
     
    // Clean (delete) all elements that have been stored
    // $ mem-> flush ();
     
    // Get the data in memcache
    echo $ mem-> get ('mystr'). '<br />';
     
    // Add elements to the memcache server
    $ mem-> add ('myarr', array ('1' => 'aaa', '2' => 'bb', '3' => 'cc'), MEMCACHE_COMPRESSED, 3600);
 
    var_dump ($ mem-> get ('myarr'));
    echo '<br />';
     
     
    class Person {
        var $ name = 'shawnking';
        var $ sex = 'Male';
    }
     
    // Add elements to the memcache server
    $ mem-> add ('myobj', new Person);
     
    var_dump ($ mem-> get ('myobj'));
    echo '<br />';
     
     
    // Get version information of memcache
    echo 'Version:', $ mem-> getVersion ();
     
    // Get the parameter information of memcache
    echo '<pre>';
    print_r ($ mem-> getStats ());
    echo '</ pre>';
     
    // Close the connection to the memcached server. This function does not close the persistent connection. The persistent connection is only closed when the web server is shut down / restarted. Correspondingly, you can also use
    $ mem-> close ();
   
     Where does PHP use memcache
            a, the data read from the database (select) using memcache processing
        Normally, when we visit a page of php, we will connect to the database once and read the data in the database. If the database cannot bear the pressure when the traffic is large, we use memcache. The data will be stored in the memcache server, and an expiration time is set, so that you do not need to go to the database to read the data before the expiration time. This can greatly improve the performance of the website. Up very fast). Below I posted the sample code for using memcache in the database:

<? php
    // Instantiate a memcache object
    $ mem = new Memcache;
     
    // connect memcache server
    $ mem-> connect ('localhost', 11211);
     
    / **
     * Note:
     * 1. The same project is installed twice, and the key must have a prefix
     * $ key = 'a_test';
     * $ key = 'b_test';
     * 2. Use the sql statement as a subscript, so that only one copy of the data of the same sql statement is stored in memcache
     * /
     
    $ sql = 'SELECT * FROM test';
    $ key = substr (md5 ($ sql), 10, 8);
     
    // Get data from memcache server
    $ data = $ mem-> get ($ key);
     
     
    // Determine if there is data in memcache
    if (! $ data) {
         
        $ mysqli = new mysqli ('localhost', 'root', '123456', 'testdb');
         
        $ result = $ mysqli-> query ($ sql);
         
        $ data = array ();
         
        while ($ row = $ result-> fetch_assoc ()) {
            $ data [] = $ row;
        }
         
        $ result-> free (); // Free up memory
        $ mysqli-> close (); // Disconnect mysql connection
         
        // Store data to the memcache server, and also set the expiration time (in seconds)
        $ mem-> set ($ key, $ data, MEMCACHE_COMPRESSED, 3600);
         
     }
      
     print_r ($ data);
     $ mem-> close (); // Close memcache connection
  
    b, used in session control session
                Write session information to the memcache server

<? php

/ **
* Session saved to memcache class
* /
class MemSession {
Ranch
private static $ handler = null;
private static $ lifetime = null;
private static $ time = null;
const NS = 'session_';
Ranch
/ **
* Initialization function
* /
private static function init ($ handler) {
self :: $ handler = $ handler;
self :: $ lifetime = ini_get ('session.gc_maxlifetime');
Ranch
self :: $ time = time ();
}
Ranch
public static function start (Memcache $ memcache) {
self :: init ($ memcache);
Ranch
session_set_save_handler (
array (__ CLASS__, 'open');
array (__ CLASS__, 'close');
array (__ CLASS__, 'read');
array (__ CLASS__, 'write');
array (__ CLASS__, 'destrory');
array (__ CLASS__, 'gc');
);
session_start ();
}
Ranch
public static function open ($ path, $ name) {
return true;
}
Ranch
public static function close () {
return true;
}
Ranch
public static function read ($ PHPSESSID) {
$ out = self :: $ handler-> get (self :: $ session_key ($ PHPSESSID));
Ranch
if ($ out === false || $ out = null)
return '';
return $ out;
}
Ranch
public static function write ($ PHPSESSID, $ data) {
$ method = $ data? 'set': 'replace';
return self :: $ handler-> $ method (self :: $ session_key ($ PHPSESSID),
$ data, MEMCACHE_COMPRESSED, self :: $ lifetime);
}
Ranch
public static function destroy ($ PHPSESSID) {
return sele :: $ handler-> delete (self :: $ session_key ($ PHPSESSID)
);
}
Ranch
public static function gc ($ lifetime) {
return true;
}
Ranch
private static session_key ($ PHPSESSID) {
$ session_key = self :: NS. $ PHPSESSID;
return $ session_key;
}
}
Ranch
$ memcache = new Memcache;
Ranch
$ memcache-> connect ('localhost', 11211) or die ('could not connect!');
Ranch
MemSession :: start ($ memcache);


      Fourth, the security of memcache (do not let others access)
             1. Intranet connection

             2.Set up a firewall

                

                 iptables -A INPUT -p tcp -dport 11211 -j DROP to deny all access,

                 Set the accessible IP

                 iptables -A INPUT -p tcp -s 192.168.1.111 -dport 11211 -j ACCEPT

                 iptables -A INPUT -p udp -s 192.168.1.111 -dpost 11211 -j ACCEPT
Related Article

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.