Question

How do I from PHP code if a PECL extension is installed or not?

I want gracefully handle the case when an extension is not installed.

Was it helpful?

Solution 4

Couple different ways. You can just check for the existence of the class, or even a function: class_exists, function_exists, and get_extension_funcs:

<?php
if( class_exists( '\Memcached' ) ) {
    // Memcached class is installed
}

// I cant think of an example for `function_exists`, but same idea as above

if( get_extension_funcs( 'memcached' ) === false ) {
    // Memcached isn't installed
}

You can also get super complicated, and use ReflectionExtension. When you construct it, it will throw a ReflectionException. If it doesnt throw an exception, you can test for other things about the extension (like the version).

<?php
try {
    $extension = new \ReflectionExtension( 'memcached' );
} catch( \ReflectionException $e ) {
    // Extension Not loaded
}

if( $extension->getVersion() < 2 ) {
    // Extension is at least version 2
} else {
    // Extension is only version 1
}

OTHER TIPS

I think the normal way would be to use extension-loaded.

if (!extension_loaded('gd')) {
    // If you want to try load the extension at runtime, use this code:
    if (!dl('gd.so')) {
        exit;
    }
}

get_loaded_extensions fits the bill.

Use like this:

$ext_loaded = in_array('redis', get_loaded_extensions(), true);

Have you looked at get_extension_funcs?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top