How to Check If a PHP Extension Is Loaded
This article explains how to use the built-in
extension_loaded() function in PHP to verify if a specific
extension is active and available. You will learn the syntax of the
function, see practical code examples, and discover how to handle
missing extensions gracefully in your web applications.
The extension_loaded() function is a native PHP feature
used to determine whether a specific extension is compiled and loaded
into your PHP environment. This is highly useful when your application
relies on external libraries—such as GD for image processing, PDO for
database connections, or cURL for making HTTP requests—and you want to
prevent fatal errors before executing extension-specific code.
Syntax of extension_loaded()
The function accepts a single string parameter representing the name
of the extension and returns a boolean value (true or
false).
bool extension_loaded(string $name)The extension name passed to the function is case-insensitive,
meaning extension_loaded('curl') and
extension_loaded('cURL') will yield the same result.
Practical Code Example
Here is a basic example demonstrating how to check for the
mbstring extension before using its functions:
<?php
if (extension_loaded('mbstring')) {
echo "The mbstring extension is enabled.";
// Securely use mbstring functions here
$length = mb_strlen("Hello World");
} else {
echo "Error: The mbstring extension is required but not loaded.";
}
?>How to Find the Correct Extension Name
To find the exact name of the extension you want to check, you can
run a quick PHP script using the get_loaded_extensions()
function. This returns an array of all currently active extensions on
your server:
<?php
print_r(get_loaded_extensions());
?>Alternatively, you can run the command php -m in your
command line terminal to list all enabled modules. Use the exact
spelling from these outputs as the string argument for
extension_loaded().