52

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.

Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

10 Answers10

56

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.
}
mauris
  • 42,982
  • 15
  • 99
  • 131
  • 6
    Good info, but keep in mind all the class_exists function is telling you is if there's ANY class in the defined include/require hierarchy named Memcache. – Alana Storm Sep 23 '09 at 02:39
  • 1
    Would any other class name itself "memcache"? does any framework or library do this? – Robin Rodricks Sep 23 '09 at 02:51
  • 3
    @Jeremy I've never seen anything else called memcache, so you're likely safe, especially all you have on the page is class_exists() – Darryl Hein Sep 23 '09 at 02:54
  • 2
    alternative would be checking the extension version? phpversion('memcache') – mauris Sep 23 '09 at 03:05
  • 4
    better yet: `if(class_exists('Memcache',false))` which works fine with autoload() – romaninsh Dec 09 '12 at 12:16
  • If another Memcache class deliberately autoloads when Memcache is not found, it means to say that it is intended to override. setting false to `$autoload` is not recommended. – mauris Dec 09 '12 at 22:19
  • Does this actually tell you if the memcached daemon is running, though? (Or is it somehow integrated with Apache?) – Simon East Jun 20 '14 at 06:19
  • 1
    @Simon, no this doesn't. Best bet is to use your OS task manager and check if the process is running. – mauris Jun 20 '14 at 09:04
  • Not sure why this has been marked as the correct answer. `class_exists` will only tell you if there is any class called 'Memcache' available, whereas using `extension_loaded` will tell you if php has loaded the Memcache extension or not, which i believe is what the OP is asking. – buffcoredave Dec 09 '14 at 11:11
  • If checking for memcached (note the additional 'd') `if(class_exists('Memcached')){ // Memcached is enabled. }` – ChristoKiwi Apr 27 '16 at 05:06
28

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';
}

?>
Simon East
  • 55,742
  • 17
  • 139
  • 133
Bijay Rungta
  • 990
  • 9
  • 16
  • Make sure you install `php5-memcache` PHP Library to check this instead of `php5-memcached` The Code Snippet is also posted at https://gist.github.com/rungss/5185410 – Bijay Rungta Mar 18 '13 at 06:35
  • 2
    +1 for posting the only answer that actually tests for a valid memcache daemon, rather than just checking for the presence of the PHP extension. – Simon East Jun 20 '14 at 07:04
  • 2
    Reminder that Memcache != Memcached, so if you're looking to test for Memcached, in addition to using class_exists('Memcached'), you'll have to $memcache->addServer($server, 11211, 1); instead of ->connect(), and do ->set('data', $aData, 300); instead of the ->set() above. – Greg Oct 23 '16 at 05:01
27

why not use the extension_loaded() function?

J.C. Inacio
  • 4,442
  • 2
  • 22
  • 25
22

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.

hlasso
  • 389
  • 1
  • 3
  • 7
  • 2
    I don't think this tells you if the memcached daemon is actually running, though... :-( – Simon East Jun 20 '14 at 07:05
  • 3
    @Simon, that is correct. If you want to check whether memcache is running you can run : _ps -ef | grep memcache_ This will work on Linux as long as you have the correct permissions (I ran it as root). – hlasso Jun 24 '14 at 15:17
11

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
}
Community
  • 1
  • 1
antitoxic
  • 3,746
  • 1
  • 37
  • 46
10

You have several options ;)

$memcache_enabled = class_exists('Memcache');
$memcache_enabled = extension_loaded('memcache');
$memcache_enabled = function_exists('memcache_connect');
mgutt
  • 5,867
  • 2
  • 50
  • 77
8

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
danno
  • 277
  • 3
  • 7
5

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');
x29a
  • 1,761
  • 1
  • 24
  • 43
4

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.

Paul Dragoonis
  • 2,315
  • 1
  • 16
  • 22
2

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!

Nassim
  • 2,879
  • 2
  • 37
  • 39