How to check if memcache or memcached is installed for PHP?
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.
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.
}
why not use the extension_loaded() function?
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';
}
?>
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.
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
}