(PHP 4, PHP 5, PHP 7, PHP 8)
dl — Carga una extensión PHP dinámicamente
Carga la extensión PHP extension_filename
dinámicamente.
Utilice la función extension_loaded() para verificar si una extensión está cargada o no. Esta función funciona tanto con extensiones nativas como con extensiones cargadas dinámicamente (vía el php.ini o dl()).
Esta función solo está disponible para los SAPI CLI e integrados, y el SAPI CGI cuando se ejecuta desde la línea de comandos.
extension_filenameEste parámetro es solo el nombre de archivo de la extensión, que depende de la plataforma. Por ejemplo la extensión sockets (si compilada como módulo compartido, y no por defecto), se llamará sockets.so bajo Unix, y php_sockets.dll bajo Windows.
La carpeta desde la cual se cargan las extensiones depende de la plataforma:
Windows - Si no se indica explícitamente en el archivo php.ini, la extensión se carga desde C:\php5\ por defecto.
Unix - Si no se indica explícitamente en el archivo php.ini, la carpeta de extensiones depende de
--enable-debug
o no
Zend Thread Safety) o no
ZEND_MODULE_API_NO
(versión interna de API de módulo Zend, que en realidad es la fecha
en que se realizó una modificación importante de la API, por ejemplo
20010901)
<install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO,
por ejemplo
/usr/local/php/lib/php/extensions/debug-non-zts-20010901
o
/usr/local/php/lib/php/extensions/no-debug-zts-20010901.
Esta función retorna true en caso de éxito o false si ocurre un error. Si la funcionalidad de carga de módulos no está
disponible, o ha sido desactivada (desactivando la directiva
enable_dl
en el php.ini) se emitirá un E_ERROR y
la ejecución del script será detenida. Si la función
dl() falla porque la biblioteca no pudo ser encontrada,
dl() retornará false y emitirá un mensaje de advertencia
E_WARNING .
Ejemplo #1 Ejemplos con dl()
<?php
// Carga para todas las plataformas
if (!extension_loaded('sqlite')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('php_sqlite.dll');
} else {
dl('sqlite.so');
}
}
// O usar la constante PHP_SHLIB_SUFFIX
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>Nota:
dl() es sensible a mayúsculas/minúsculas en plataformas Unix.
dl is awkward because the filename format is OS-dependent and because it can complain if the extension is already loaded. This wrapper function fixes that:
<?php
function load_lib($n, $f = null) {
return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
}
?>
Examples:
<?php
// ensure we have SSL and MySQL support
load_lib('openssl');
load_lib('mysql');
// a rare few extensions have a different filename to their extension name, such as the image (gd) library, so we specify them like this:
load_lib('gd', 'gd2');
?><?php
function dl_local( $extensionFile ) {
//make sure that we are ABLE to load libraries
if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
die( "dh_local(): Loading extensions is not permitted.\n" );
}
//check to make sure the file exists
if( !file_exists( $extensionFile ) ) {
die( "dl_local(): File '$extensionFile' does not exist.\n" );
}
//check the file permissions
if( !is_executable( $extensionFile ) ) {
die( "dl_local(): File '$extensionFile' is not executable.\n" );
}
//we figure out the path
$currentDir = getcwd() . "/";
$currentExtPath = ini_get( "extension_dir" );
$subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
unset( $matches );
//lets make sure we extracted a valid extension path
if( !(bool)$subDirs ) {
die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
}
$extPathLastChar = strlen( $currentExtPath ) - 1;
if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
$subDirs--;
}
$backDirStr = "";
for( $i = 1; $i <= $subDirs; $i++ ) {
$backDirStr .= "..";
if( $i != $subDirs ) {
$backDirStr .= "/";
}
}
//construct the final path to load
$finalExtPath = $backDirStr . $currentDir . $extensionFile;
//now we execute dl() to actually load the module
if( !dl( $finalExtPath ) ) {
die();
}
//if the module was loaded correctly, we must bow grab the module name
$loadedExtensions = get_loaded_extensions();
$thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];
//lastly, we return the extension name
return $thisExtName;
}//end dl_local()
?>