Code to store PHP sessions within memcached.

Kevin Burton burton at tailrank.com
Fri Nov 17 05:30:38 UTC 2006


Someone wanted the PHP code were were using to store our sessions within
memcached.

Well here you go.

replace tailrank_ to something less proprietary.... and you'll need your own
version of tailrank_memcache_get_instance to get a copy of your memcached
object.

you to call session_start() at the beginning of your script and
session_commit() at the end.

you'll also need to change the domain from tailrank.com to your domain
(obviously)

If you make any changes or fix any bugs please let me know.

This is hereby licensed under the GPL, BSD, and public domain so have fun!
:)

<?php

/*
 * Send mail but also include the From header.
 */
function tailrank_session_start() {

    //For machines that already have this session loaded this will merely be
    //redundant....

    global $_SESSION;
    $my_memcache = tailrank_memcache_get_instance();

    $cookie = $_COOKIE[ "SESSIONID" ];

    if ( $cookie != null ) {

        $key = "session3:" . $cookie;
        $session_data = $my_memcache->get( $key );

        if ( $session_data != null ) {
            $_SESSION = unserialize( $session_data );
        }

    } else {

        //call the default php session start code to init the session on
this
        //client.

        srand((double)microtime()*1000000);
        $cookie = rand( 0, 100000000000 );

        $_COOKIE[ "SESSIONID" ] = $cookie;

        //create a new local aray for the session.
        $_SESSION=array();

        $expire = time() + 365 * 24 * 60 * 60 * 24;
        setcookie( 'SESSIONID', $cookie, $expire, "/", ".tailrank.com" );

    }

}

function tailrank_session_commit() {

    //serialze $_SESSION

    global $_SESSION;
    $my_memcache = tailrank_memcache_get_instance();

    if ( $_SESSION != null ) {

        $session_data = serialize( $_SESSION );
        $cookie = $_COOKIE[ "SESSIONID" ];
        $key = "session3:" . $cookie;

        $my_memcache->set( $key, $session_data, false, 600 );

    }

}

?>

-- 
Founder/CEO Tailrank.com
Location: San Francisco, CA
AIM/YIM: sfburtonator
Skype: burtonator
Blog: feedblog.org
Cell: 415-637-8078
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.danga.com/pipermail/memcached/attachments/20061116/70203a02/attachment.htm


More information about the memcached mailing list