dl

(PHP 4, PHP 5, PHP 7)

dlЗавантажує розширення PHP під час виконання

Опис

bool dl ( string $library )

Завантажує розширення PHP, що задається через параметр library.

Використовуйте extension_loaded(), щоб перевірити, чи задане розширення вже доступне, чи ні. Ця функція працює в обох варіантах: для вбудованих розширень та для тих, що динамічно завантажуються (тобто для завантажених через php.ini, та для завантажених через dl()).

Увага

Ця функція видалена з деяких SAPI в PHP 5.3.

Параметри

library

Через цей параметр передається тільки назва файла розширення для завантаження, яка також залежить від платформи. Наприклад, розширення sockets (якщо скомпільоване як завантажуваний модуль, а не як початковий модуль!) буде називатись sockets.so на Unix-платформах, в той час як на Windows-платформах воно буде називатись php_sockets.dll.

Директорія, звідки розширення завантажується, залежить від платформи:

Windows - Якщо явно не підключено у файлі php.ini, початково, розширення завантажується із C:\php4\extensions\ (PHP 4) або C:\php5\ (PHP 5).

Unix - Якщо явно не підключено у файлі php.ini, початково, директорія розширення залежить від

  • чи було зібрано PHP з параметром --enable-debug, чи ні
  • чи було зібрано PHP з підтримкою (експерементального) ZTS (Zend Thread Safety), чи ні
  • поточний внутрішній номер ZEND_MODULE_API_NO (внутрішній номер API Zend-модуля, який, як правило, є датою major-зміни модуля API, наприклад 20010901)
Беручи до уваги вищезазначене, маємо такі директорії для розширень за промовчанням <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, наприклад /usr/local/php/lib/php/extensions/debug-non-zts-20010901 або /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Значення, що повертаються

Повертає TRUE в успішному випадку або FALSE в разі помилки. Якщо механізм завантаження модулів недоступний чи відключений (або через значення off для директиви enable_dl, або через включення безпечний режим у файлі php.ini), то видається повідомлення помилки E_ERROR та припиняється виконання. Якщо dl() провалюється через те, що зазначену бібліотеку не можна завантажити, на додаток до FALSE буде видаватись повідомлення E_WARNING.

Приклади

Приклад #1 Використання dl()

<?php
// Приклад завантаження розширення, виходячи з ОС
if (!extension_loaded('sqlite')) {
    if (
strtoupper(substr(PHP_OS03)) === 'WIN') {
        
dl('php_sqlite.dll');
    } else {
        
dl('sqlite.so');
    }
}

// Або, використовуючи константу PHP_SHLIB_SUFFIX, що доступна починаючи з PHP 4.3.0
if (!extension_loaded('sqlite')) {
    
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' '';
    
dl($prefix 'sqlite.' PHP_SHLIB_SUFFIX);
}
?>

Журнал Змін

Версія Опис
5.3.0 dl() виключено в деяких SAPI, в зв'язку з нестабільністю. Для функції dl() доступними SAPI залишаються тільки CLI та Embed. Замість неї використовуйте Директиви Завантаження Розширень.

Примітки

Зауваження:

Функція dl() НЕ підтримується коли PHP зібрана з підтримкою ZTS. Замість неї використовуйте Директиви Завантаження Розширень.

Зауваження:

dl() є регістро-чутливою на Unix-платформах.

Зауваження: Ця функція блокується, коли PHP запускається в безпечному режимі.

Прогляньте Також

add a note add a note

User Contributed Notes 7 notes

up
16
shaunspiller at spammenot-gmail dot com
15 years ago
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');

?>
up
11
K. C.
9 years ago
It would be nice to know which SAPIs removed the function.

Telling me 'This function has been removed from some SAPIs in PHP 5.3.' is pretty much useless and I feel mocked. Or do the writers of the documentation don't know from which SAPIs it has been removed?
up
0
mag_2000 at front dot ru
18 years ago
<?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()

?>
up
-1
anrdaemon at freemail dot ru
7 years ago
Like with eval(), the only correct way to use dl() is to not use it.
Test if a function(s) you intend to use are available.
If not, complain to the user or implement a workaround.
Not to mention dl() issues in a multithreading environment.
up
-1
endofyourself at yahoo dot com
20 years ago
If you need to load an extension from the CURRENT local directory because you do not have privelages to place the extension in your servers PHP extensions directory, this function i wrote may be of use to you

<?php
/*
    Function: dl_local()
    Reference: http://us2.php.net/manual/en/function.dl.php
    Author: Brendon Crawford <endofyourself |AT| yahoo>
    Usage: dl_local( "mylib.so" );
    Returns: Extension Name (NOT the extension filename however)
    NOTE:
        This function can be used when you need to load a PHP extension (module,shared object,etc..),
        but you do not have sufficient privelages to place the extension in the proper directory where it can be loaded. This function
        will load the extension from the CURRENT WORKING DIRECTORY only.
        If you need to see which functions are available within a certain extension,
        use "get_extension_funcs()". Documentation for this can be found at
        "http://us2.php.net/manual/en/function.get-extension-funcs.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()

?>
up
-9
Anonymous
13 years ago
this function errors out as the dl() cannot take the absolute path..."Warning: dl() [function.dl]: Temporary module name should contain only filename in /home/..."
up
-5
fabrizim at owlwatch dot com
10 years ago
As noted in the documentation:

Changelog 5.3: dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead.

If using PEAR libraries that try to load extensions, like Image_Transform which will try to load ImageMagik, and the "enable_dl" directive is set to 1 in your php.ini, you may end up with a hard to find error (white screen of death).

One "solution" is to change the enable_dl directive to 0 in the php.ini. It may have adverse affects if you are using php on command line that requires the "dl" function, but I think in most cases its okay.
To Top