How to check if memcache or memcached is installed for PHP?

PhpApacheScriptingWebserver

Php Problem Overview


How do I test if memcache or memcached (for PHP) is installed on my Apache webserver?

> Memcache is a caching daemon designed especially for dynamic web applications to decrease database load by storing objects in memory.

Php Solutions


Solution 1 - Php

You can look at phpinfo() or check if any of the functions of memcache is available. Ultimately, check whether the Memcache class exists or not.

e.g.

if(class_exists('Memcache')){
  // Memcache is enabled.
}

Solution 2 - Php

why not use the extension_loaded() function?

Solution 3 - Php

Use this code to not only check if the memcache extension is enabled, but also whether the daemon is running and able to store and retrieve data successfully:

<?php
if (class_exists('Memcache')) {
    $server = 'localhost';
    if (!empty($_REQUEST['server'])) {
        $server = $_REQUEST['server'];
    }
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect($server);

    if ($isMemcacheAvailable) {
        $aData = $memcache->get('data');
        echo '<pre>';
        if ($aData) {
            echo '<h2>Data from Cache:</h2>';
            print_r($aData);
        } else {
            $aData = array(
                'me' => 'you',
                'us' => 'them',
            );
            echo '<h2>Fresh Data:</h2>';
            print_r($aData);
            $memcache->set('data', $aData, 0, 300);
        }
        $aData = $memcache->get('data');
        if ($aData) {
            echo '<h3>Memcache seem to be working fine!</h3>';
        } else {
            echo '<h3>Memcache DOES NOT seem to be working!</h3>';
        }
        echo '</pre>';
    }
}
if (!$isMemcacheAvailable) {
    echo 'Memcache not available';
}

?>

Solution 4 - Php

I know this is an old thread, but there's another way that I've found useful for any extension.

Run

php -m | grep <module_name>

In this particular case:

php -m | grep memcache

If you want to list all PHP modules then:

php -m

Depending on your system you'd get an output similar to this:

[PHP Modules]
apc
bcmath
bz2
... lots of other modules ...
mbstring
memcache
 ... and still more modules ...
zip
zlib

[Zend Modules]

You can see that memcache is in this list.

Solution 5 - Php

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

Solution 6 - Php

You have several options ;)

$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');

Solution 7 - Php

It may be relevant to see if it's running in PHP via command line as well-

<path-to-php-binary>php -i | grep memcache

Solution 8 - Php

I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio

<?php
if(!extension_loaded('Memcache'))
{
    die("Memcache extension is not loaded");
}

if (!class_exists('Memcache')) 
{
    die('Memcache class not available');
}

$memcacheObj = new Memcache;
if(!$memcacheObj)
{
    die('Could not create memcache object');
}

if (!$memcacheObj->connect('localhost')) 
{
    die('Could not connect to memcache server');
}

// testdata to store in memcache
$testData = array(
    'the' => 'cake',
    'is' => 'a lie',
);

// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    if(!$memcacheObj->set('data', $testData, 0, 300))
    {
        die('Memcache could not set the data');
    }
}

// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    die('Memcache is not responding with data');
}

if($aData !== $testData)
{
    die('Memcache is responding but with wrong data');
}
 
die('Memcache is working fine');

Solution 9 - Php

The best approach in this case is to use extension_loaded() or function_exists() they are equally as fast.

You can see evidence here:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Memcached.php#L140

Bear in mind that some PHP extensions such as APC have php.ini settings that can disable them even though the extension may be loaded. Here is an example of how to check against that also:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Apc.php#L79

Hope this helps.

Solution 10 - Php

this is my test function that I use to check Memcache on the server

<?php     
public function test()
 {
 	// memcache test - make sure you have memcache extension installed and the deamon is up and running
	$memcache = new Memcache;
	$memcache->connect('localhost', 11211) or die ("Could not connect");
	
	$version = $memcache->getVersion();
	echo "Server's version: ".$version."<br/>\n";
	
	$tmp_object = new stdClass;
	$tmp_object->str_attr = 'test';
	$tmp_object->int_attr = 123;
	
	$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
	echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
	
	$get_result = $memcache->get('key');
	echo "Data from the cache:<br/>\n";
	
	var_dump($get_result);
 }

if you see something like this

    Server's version: 1.4.5_4_gaa7839e
    Store data in the cache (data will expire in 10 seconds)
    Data from the cache:
    object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }

it means that everything is okay

Cheers!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobin RodricksView Question on Stackoverflow
Solution 1 - PhpmaurisView Answer on Stackoverflow
Solution 2 - PhpJ.C. InacioView Answer on Stackoverflow
Solution 3 - PhpBijay RungtaView Answer on Stackoverflow
Solution 4 - PhphlassoView Answer on Stackoverflow
Solution 5 - PhpantitoxicView Answer on Stackoverflow
Solution 6 - PhpmguttView Answer on Stackoverflow
Solution 7 - PhpdannoView Answer on Stackoverflow
Solution 8 - Phpx29aView Answer on Stackoverflow
Solution 9 - PhpPaul DragoonisView Answer on Stackoverflow
Solution 10 - PhpNassimView Answer on Stackoverflow