• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • PHP and Redis Server

    Blogs20122012-07-19


    PHP and Redis Server

    Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

    Redis server can be used as a session handler, which is especially useful if you are using a multi-server architecture behind a load balancer.
    Redis also has a publish/subscribe system, which is great for creating an online chat or a live booking system.
    I used Redis server with NodeJS before; however and definitely, Redis Server is also available for PHP. Here is a helpful article:

    http://phpmaster.com/an-introduction-to-redis-in-php-using-predis/

    The following are the steps to install Redis-server, and make it work in PHP.

    //1. install redis-server
    wget http://redis.googlecode.com/files/redis-2.2.4.tar.gz
    tar -zxf redis-2.2.4.tar.gz
    cd redis-2.2.4
    make
    sudo make install
    
    //2. run it, sumple way, you can also use:
    //sudo update-rc.d redis-server defaults to make it run when start.
    $ /usr/local/bin/redis-server &

    Now Redis server is done. After that, we make it work with PHP.
    For PHP, Redis client library is Predis, we can get the sources from github:

    $ git clone git://github.com/nrk/predis.git

    After install Redis server and Predis interface, we now use PHP to connect and operate the session server. A testing example like this:

    <?php
    require "predis/autoload.php";
    PredisAutoloader::register();
    
    // since we connect to default setting localhost
    // and 6379 port there is no need for extra
    // configuration. If not then you can specify the
    // scheme, host and port to connect as an array
    // to the constructor.
    try {
        $redis = new PredisClient();
    /*
        $redis = new PredisClient(array(
            "scheme" => "tcp",
            "host" => "127.0.0.1",
            "port" => 6379));
    */
        echo "Successfully connected to Redis";
    }
    catch (Exception $e) {
        echo "Couldn't connected to Redis";
        echo $e->getMessage();
    }

    Pretty simple, and should return ‘Successfully connected to Redis’. A more test for Redis key-value store is like this:

    <?php
    $redis->set("any_key", "Hi Redis for php by using predis!");
    $value = $redis->get("any_key");
    print_r($value);