dl

(PHP 4, PHP 5, PHP 7, PHP 8)

dlCarrega uma extensão do PHP durante a execução

Descrição

dl(string $library): bool

Carrega a extensão do PHP indicada pelo parâmetro library.

Use extension_loaded() para testar se uma extensão está disponível ou não. Isto funciona para extensões internas e para aquelas carregadas dinamicamente (através do php.ini ou da função dl()).

Aviso

Esta função foi removida de algumas SAPIs no PHP 5.3 e removida do PHP-FPM no PHP 7.0.0.

Parâmetros

library

Este parâmetro é somente o nome do arquivo da exdtensão a carregar o qual também depende da sua plataforma. Por exemplo, a extensão sockets (se compilada como módulo compartilhado, não o padrão!) seria chamada sockets.so em plataformas Unix enquanto é chamada php_sockets.dll na plataforma Windows.

O diretório a partir do qual a extensão é carregada depende da sua plataforma:

Windows - Se não for explicitamente definido no php.ini, a extensão é carregada a partir de C:\php4\extensions\ (PHP 4) ou C:\php5\ (PHP 5) por padrão.

Unix - Se não for explicitamente definido no php.ini, o diretório padrão das extensões depende de

  • se o PHP foi compilado com --enable-debug ou não
  • se o PHP foi compilado com suporte (experimental) ZTS (Zend Thread Safety) ou não
  • O ZEND_MODULE_API_NO (o número Zend internal module API, o que é basicamente a data onde houve uma mudança maior na API ex. 20010901)
Levando em conta o acima, o diretório padrão poderá ser <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 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha. Se a funcionalidade de carregar módulos não estiver disponível ou foi desabilitada (por desligar enable_dl no php.ini) então um erro E_ERROR é disparado e a execução é interrompida. Se dl() falhar porque a biblioteca especificada não puder ser carregada, além de retornar false uma mensagem E_WARNING é emitida.

Exemplos

Exemplo #1 Exemplosdl()

<?php
// Example loading an extension based on OS
if (!extension_loaded('sqlite')) {
if (
strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('php_sqlite.dll');
} else {
dl('sqlite.so');
}
}

// Or, the PHP_SHLIB_SUFFIX constant is available as of PHP 4.3.0
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

Changelog

Versão Descrição
7.0.0 dl() foi desabilitado do PHP-FPM.
5.3.9 dl() está habilitado no PHP-FPM, mas com o uso desencorajado.
5.3.0 dl() foi desabilitada em algumas SAPIs por conta de problemas de estabilidade. Somente as SAPIs que permitem dl() são a CLI e Embed. Utilize a Extension Loading Directives nos demais casos.

Notas

Nota:

dl() não é suportada no PHP compilado com suporte ZTS support. Utilize as the diretivas de carregamento de extensões nesse caso.

Nota:

dl() é sensível maiúsculas/minúsculas nas plataformas Unix.

Veja Também

add a note

User Contributed Notes 4 notes

up
10
shaunspiller at spammenot-gmail dot com
14 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
mag_2000 at front dot ru
17 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
-3
anrdaemon at freemail dot ru
6 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
-3
endofyourself at yahoo dot com
19 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()

?>
To Top