downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

extension_loaded> <cli_set_process_title
[edit] Last updated: Fri, 17 May 2013

view this page in

dl

(PHP 4, PHP 5)

dlCharge une extension PHP à la volée

Description

bool dl ( string $library )

Charge l'extension PHP library à la volée.

Utilisez la fonction extension_loaded() pour vérifier qu'une extension est chargée ou non. Cette fonction travaille aussi bien avec les extensions natives qu'avec les extensions dynamiquement chargées (via le php.ini ou dl()).

Avertissement

Cette fonction a été supprimée du SAPI en PHP 5.3.

Liste de paramètres

library

Ce paramètre est seulement le nom de fichier de l'extension, qui dépend de votre plate-forme. Par exemple l'extension sockets (si compilée comme module partagé, et non par défaut), sera appelée sockets.so sous Unix, et php_sockets.dll sous Windows.

Le dossier à partir duquel sont chargées vos extensions dépend de votre plate-forme :

Windows - S'il n'est pas explicitement indiqué dans le fichier php.ini, le dossier des extensions est c:\php4\extensions\ (PHP 4) ou C:\php5\ (PHP 5) par défaut.

Unix - S'il n'est pas explicitement indiqué dans le fichier php.ini, le dossier des extensions dépend de

  • Si PHP a été compilé avec l'option --enable-debug ou non
  • Si PHP a été compilé avec le support (expérimental) de ZTS (Zend Thread Safety) ou non
  • de la constante interne ZEND_MODULE_API_NO (version interne de module d'API Zend, qui est en réalité la date à laquelle une modification importante de l'API a été faite, par exemple 20010901)
En prenant ces paramètres en considération, le dossier des extensions vaut alors <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 ou /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Valeurs de retour

Cette fonction retourne TRUE en cas de succès ou FALSE si une erreur survient. Si la fonctionnalité de chargement de module n'est pas disponible, ou a été désactivée (soit en désactivant la directive enable_dl ou en activant le safe mode dans le php.ini) une E_ERROR sera émise et l'exécution du script sera stoppée. Si la fonction dl() échoue parce que la bibliothèque n'a pu être trouvée, dl() retournera FALSE et émettra un message d'alerte E_WARNING.

Exemples

Exemple #1 Exemples avec dl()

<?php
// Chargement pour toutes plates-formes
if (!extension_loaded('sqlite')) {
    if (
strtoupper(substr(PHP_OS03)) === 'WIN') {
        
dl('php_sqlite.dll');
    } else {
        
dl('sqlite.so');
    }
}

// Mais la constante PHP_SHLIB_SUFFIX est disponible depuis PHP 4.3.0
if (!extension_loaded('sqlite')) {
    
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' '';
    
dl($prefix 'sqlite.' PHP_SHLIB_SUFFIX);
}
?>

Historique

Version Description
5.3.0 dl() est maintenant désactivé dans quelques SAPIs en raison de son instabilité. Le seul SAPI qui active dl() sont CLI et Embed. Utilisez les directives de chargement d'extension à la place.

Notes

Note:

dl() n'est pas supporté lorsque PHP est compilé avec le support ZTS. Utilisez les directives de chargement d'extension à la place.

Note:

dl() est sensible à la casse sur les plates-formes Unix.

Note: Cette fonction est désactivée par le safe-mode

Voir aussi



extension_loaded> <cli_set_process_title
[edit] Last updated: Fri, 17 May 2013
 
add a note add a note User Contributed Notes dl - [10 notes]
up
1
mag_2000 at front dot ru
7 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
0
Anonymous
2 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
0
shaunspiller at spammenot-gmail dot com
4 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
-1
docey
7 years ago
just some note to loading modules, they do not have to
be executable.

some examples below check for this but if an module is
not executable is does not mean you cant use it. it just
needs to be readable NOT executable.

although some modules might need this perhaps for some
reason i cannot think of, so here an example,

<?php
// fails to load mysql although it could be loaded.
if(is_executable("mysql.so")){
 
dl("mysql.so");
}

// loads mysql
if(is_readable("mysql.so")){
 
dl("mysql.so");
}
?>

watch out with this, as you can see mysql.so would not be
loaded and the script would fail. because its checked for
executable permissions although these are not needed.
up
0
fabrizim at owlwatch dot com
15 days 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.
up
-1
CLI workaround
4 years ago
NOTE:  This only works using the CLI

If you need to use dl() with the CLI, but you get this warning:

"PHP Warning:  dl(): Dynamically loaded extensions aren't enabled"

Then the 'enable_dl' setting in the php.ini needs to be set to 'On' - the set_ini() function does not work with this INI option.

If, however, you do not wish (or don't have access) to alter the system php.ini, then you can do the following:

<?php

if ( !ini_get('enable_dl') ) {
   
exec("php -d enable_dl=On $argv[0]");
    exit;
}

?>

This simply calls itself and defines the enable_dl INI entry on the command line so you dont have to start the script with options in the first place (or use another script to call it.)
up
-1
james at gogo dot co dot nz
7 years ago
WARNING: enable_dl/dl()
*********************

There is an exploit circulating currently which takes advantage of dl() to inject code into Apache which causes all requests to all virtual hosts to be redirected to a page of the attackers choice.

All operators of shared web hosting servers with Apache and PHP should disable dl() by setting enable_dl to off otherwise your servers are vulnerable to this exploit.

This exploit is generally known as flame.so (the object that is loaded into Apache) and flame.php (the php script that loads it).

Google gives more information:
http://www.google.co.nz/search?q=flame.so+flame.php
up
-1
endofyourself at yahoo dot com
9 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
-2
buildsmart at daleenterprise dot com
6 years ago
I recently came across this under PHP 4.4.4, it seems that the dl(); function generates an error/warning about registering the function if a test is done on an extension that is pre-loaded in the php.ini file (extension=gd.so).
<?php
$gd_is_shared           
= "shared-library";

if (
function_exists('ImageCreateFromPNG') && !@dl('gd.so')) {
   
$gd_is_shared = "embedded";
}

print
$gd_is_shared;
?>

The only purpose of this test is to determine if it is an embedded extension or a loaded extension.

I don't see this error occur under PHP 5.1.6 or PHP 5.2.0.

The test platform is Mac OS X 10.3.9 and Mac OS X 10.4.8
up
-2
tychay at php dot net
9 years ago
MacOS makes a distinction between dynamically loadable shared libraries and loadable modules of code (bundles). The former has an extension .dylib and the latter has an extension .so. The former is in Mac-O and the latter is in ELF.

Thus PHP's extensions are built as .so whereas the symbol PHP_SHLIB_SUFFIX is bound (currently) to .dylib. I don't think this is the correct behavior, but nonetheless, it is the behavior as of PHP-5.0.0b2-dev. Right now, the config binds to SHLIB_SUFFIX_NAME (which is correctly bound to .dylib on Mac OS X). I imagine this is related to why there is so much trouble getting dl() to work on Mac OS X. (For instance, I have no trouble phpizing in a new shared library, but when compiling in stuff as shared... much evilness!)

BTW, to get dl() to work in Mac OS X you need to install the dlcompat library (via Fink, DarwinPorts, or Gentoo ports). Remember in the case of Fink, you better make sure your environment variables are adjusted to point to where dlcompat (and your other fink libraries) are.

terry

 
show source | credits | sitemap | contact | advertising | mirror sites