Confusion using memcache with current session cresting

We have recently moved to a different host and the website is now set up on a dual servers, and we are experiencing issues where users are logged out after seconds, so I looked into it and came across memcache, which the hosts have now told me is set up with the library.

They then asked me to set my bit up, so I looked into and found a tutorial where I create a file called cache.php and add the following code -

<?php
 # Copyright 2012 John Post - StarfixIT
 # NOTE: Requires PHP version 5.3 or later with Memcache module
class cache
    {
    
        private $host = '127.0.0.1';
        private $port = '11211';
        private $memcache;
        private $lifetime;
        private $name;

        function __construct($name = false, $lifetime = 600)
        {
          //Check if Memcache is installed
            if(!class_exists("Memcache")){
                exit("You need to install memcache");
            } 
            //Check if allready connected to memcached
            if (isset($_GLOBALS["memcache"])) {
                //Yes, use old connection
                $this->memcache = $_GLOBALS["memcache"];
            } else {
                //No, make new connection
                $this->memcache = new Memcache;
                $this->memcache->connect($this->host, $this->port);
                $_GLOBALS["memcache"] = $this->memcache;
            }
            //Set global livetime
            $this->lifetime = $lifetime;
            
            //Set global name
            if ($name !== false) {
                $this->name = $this->makeNameOk($name);
            }
        }
        
        //Public function to set the name
        public function setName($name)
        {
            $this->name = $this->makeNameOk($name);
        }
        
        //Public function to set the cache, livetime optional
        public function setCache($data, $lifetime = false)
        {
            $lifetime = $lifetime === false ? $this->lifetime : $this->lifetime;
            $this->memcache->set($this->name, $data, MEMCACHE_COMPRESSED, $lifetime);
        }
        
        //Public function to get the cache, optional name
        public function getCache($name = false)
        {
            $name = $name === false ? $this->name : $name;
            $result = $this->memcache->get($name);
            if ($result !== false) {
                return $result;
            }
            return false;
        }
        
        //Public function to remove the data from Memcached
        public function remove( $name = false )
        {
            $name = $name === false ? $this->name : $name;
            $this->memcache->delete( $name );
        }
        
        //Function to create a clean alias
        private function makeNameOk($name)
        {
            return preg_replace('/[^A-Za-z0-9_]/', "", $name);
        }

    }

And then it says to include that on my pages where I need it, but the trouble is I have already got a way of creating a session as below on logging in

$username=$_POST['txtuser']; 
$password=md5($_POST['txtpass']); 
if ($username==$data['Username']  && $password==$data['Password'])
{
	$error1="correct";
	$_SESSION['user1']=$username;
	$_SESSION['flaglog']=1;

Then on each page after that, I have

$username=$_SESSION['user1'];
if ($_SESSION['flaglog']!=1)
{	
	header("location:index.php");
}
 else
{
$query = "SELECT * FROM Users WHERE Username='$username'";
$res = sqlsrv_query($conn, $query); 
while ($result = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) { 
$name = $result["First_Name"];
$security = $result["Admin"];
//echo $security;
}

So where I’m baffled is how to get memcache working with the way I’m set up at the moment.

When using PHP sessions, they are only local to the machine the PHP script runs on. So if you have dual servers running the same PHP scripts, then one machine will have the session and the other won’t, and when a user is sent to the machine without the session, they are considered logged out automatically. You need to add a memcache session service, in order to persist the session data between the two (or more) machines.

Or, you need to have sticky sessions through a load balancer, where the load balancer always sends the user back to the same machine they had gotten the session from.

Scott

Hi Scott,

OK yes that’s what was explained to us with regard to the dual machines, and so asked them to set up memcache for us, but where I’m stuck is how do I get what I got to work with it, or do I need to change it completely if so can I get some advice on this, or like what you say above is it something else the host needs to do.

Basically this has landed on me today and haven’t got a clue

What you are going to have to do is change your session logic to include storing and retrieving the session in Memcache. So where you create the session, you need to use the setCache() method to save the session data and where you query for the session data, you need to use the getCache() method to call up the session again. You can also use the setName() method to create the session identifier.

Are you also using memcache or memcached?

Scott

So in relation to below

$username=$_SESSION['user1'];
if ($_SESSION['flaglog']!=1)
{	
header("location:index.php");
}
else

I will use

$username=setCache('user1');
if (setCache('flaglog')!=1)
{	
header("location:index.php");
}
else

Also I just checked and its memcached

Thanks

You should be able to change your php.ini session settings to use the Memcahed extension. That way, you don’t have to change the way sessions are used within your app.

[Session]
; Handler used to store/retrieve data.
; http://www.php.net/manual/en/session.configuration.php#ini.session.save-handler
session.save_handler = memcached
session.save_path = "127.0.0.1:11211"
1 Like

Hi Fretburner,

I’m all over the place now sorry, but am going to listen very carefully to what you guys got to say, believe me.

So basically I can leave everything I got as it is, and then use the cache.php include on every page, is that bit right?

Then add what you got above to the ini file?

All you need to do to for PHP to use your memcache server for sessions is modify the php.ini file on both servers so they use the memcached rather than files (which is the default). The cache class you posted is useful for caching data that you want to be shared between servers and/or sessions, such as the results of commonly run DB queries, or other resource intensive procedures.

Thanks,

So just to clarify.

I leave everything I got as it is, there no need for me to include that cache.php, instead I use memcached and add what you gave me above (with a different IP address) to the php.ini file on each server, and that will be job done.

:confused:

:thumbsup: yep, that should get you sorted.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.