Php load dll files

Установка PHP-расширения в Windows

В Windows есть два способа загрузки PHP-расширения: скомпилировать его вместе с PHP или загрузить DLL. Загрузка заранее скомпилированного расширения является наиболее простым и предпочитаемым способом.

Для загрузки расширения, оно должно присутствовать на вашей системе в виде «.dll» файла. Все расширения автоматически и периодически компилируются командой PHP (см. следующий раздел для загрузки).

За инструкциями по компиляции расширения в PHP обратитесь к разделу «Сборка из исходников».

Для компиляции отдельного расширения (или DLL-файла), обратитесь к разделу » Сборка из исходников». Если DLL-файла нет ни в стандартной поставке PHP ни в PECL, возможно, вам придется скомпилировать его вручную.

Где найти расширение?

PHP-расширения обычно имеют имена вида «php_*.dll» (где звездочка обозначает имя расширения) и располагаются в папке «PHP\ext».

PHP поставляет расширения наиболее полезные большинству разработчиков. Такие расширения называются «основными» («core»).

Однако, если вам требуется функционал, который не предоставляется ни одним из основных расширений, возможно, нужное вам расширение есть в PECL. Библиотека расширений сообщества PHP (The PHP Extension Community Library, PECL) является хранилищем расширений PHP, предоставляя каталог и хостинг всех известных расширений для скачки и дальнейшей разработки расширений в PHP.

Если вы разработали какое-либо расширение для собственных нужд, возможно, вы захотите хранить его в PECL, так, чтобы другие также могли воспользоваться результатами вашего труда. Хорошим побочным эффектом будет неплохой шанс получить обратную связь, благодарности (надеемся, что так и будет), сообщения об ошибках и даже исправления/патчи. Пожалуйста, прочтите » публикация PECL; перед отправкой вашего расширения в PECL.

Читайте также:  Code convention java oracle

Какое расширение нужно загрузить?

  • Различные номера версий (по крайней мере первые два числа должны совпадать)
  • Различные настройки потокобезопасности
  • Различная архитектура процессора (x86, x64, . )
  • Различные настройки отладки
  • и т.д.

Помните, что настройки ваших расширений должны совпадать со всеми настройками используемого вами бинарного файла PHP. Следующий PHP-скрипт выведет вам все настройки PHP:

Пример #1 Вызов phpinfo()

Или запустите из командной строки:

Источник

Php load dll files

dl — Загружает модуль PHP во время выполнения

Описание

Загружает модуль PHP, заданный аргументом extension_filename .

Чтобы проверить, что заданный модуль уже загружен, используйте функцию extension_loaded() . Функция работает как для встроенных модулей, так и для динамически загруженных (т.е. загруженных как через php.ini , так и через dl() ).

Функция доступна только для CLI и встроенного SAPI , а также для CGI SAPI при запуске из командной строки.

Список параметров

Аргумент содержит только имя файла модуля, который требуется загрузить. Это имя зависит от платформы. Например, модуль sockets (если скомпилирован, как загружаемый модуль, а не модуль по умолчанию!) будет называться sockets.so на Unix-платформах, и php_sockets.dll в среде Windows.

Директория, из которой модуль должен быть загружен, также зависит от платформы:

Windows — Если явно не задано в php.ini , модуль будет грузиться из C:\php5\ по умолчанию.

  • PHP собран с настройкой —enable-debug или без неё
  • PHP собран с поддержкой ZTS (Zend Thread Safety) или нет
  • текущий внутренний номер ZEND_MODULE_API_NO (номер внутреннего модуля Zend API, который, как правило, является датой основного изменения API модуля, например 20010901 )

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки. Если механизм загрузки модулей недоступен или отключён (значение off настройки enable_dl в php.ini ), будет выдана ошибка E_ERROR и выполнение прекращается. Если dl() не сможет загрузить заданную библиотеку, то в дополнение к false будет выдано сообщение E_WARNING .

Примеры

Пример #1 Примеры использования dl()

// Пример загрузки модуля, основываясь на ОС
if (! extension_loaded ( ‘sqlite’ )) if ( strtoupper ( substr ( PHP_OS , 0 , 3 )) === ‘WIN’ ) dl ( ‘php_sqlite.dll’ );
> else dl ( ‘sqlite.so’ );
>
>

// Или на константе PHP_SHLIB_SUFFIX
if (! extension_loaded ( ‘sqlite’ )) $prefix = ( PHP_SHLIB_SUFFIX === ‘dll’ ) ? ‘php_’ : » ;
dl ( $prefix . ‘sqlite.’ . PHP_SHLIB_SUFFIX );
>
?>

Примечания

Замечание:

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

Смотрите также

User Contributed Notes 4 notes

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:

function load_lib ( $n , $f = null ) return extension_loaded ( $n ) or dl ((( PHP_SHLIB_SUFFIX === ‘dll’ ) ? ‘php_’ : » ) . ( $f ? $f : $n ) . ‘.’ . PHP_SHLIB_SUFFIX );
>

// 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’ );

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 —;
>

//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 ;

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.

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

/*
Function: dl_local()
Reference: http://us2.php.net/manual/en/function.dl.php
Author: Brendon Crawford
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 —;
>

//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 ;

  • Опции PHP/информационные функции
    • assert_​options
    • assert
    • cli_​get_​process_​title
    • cli_​set_​process_​title
    • dl
    • extension_​loaded
    • gc_​collect_​cycles
    • gc_​disable
    • gc_​enable
    • gc_​enabled
    • gc_​mem_​caches
    • gc_​status
    • get_​cfg_​var
    • get_​current_​user
    • get_​defined_​constants
    • get_​extension_​funcs
    • get_​include_​path
    • get_​included_​files
    • get_​loaded_​extensions
    • get_​required_​files
    • get_​resources
    • getenv
    • getlastmod
    • getmygid
    • getmyinode
    • getmypid
    • getmyuid
    • getopt
    • getrusage
    • ini_​alter
    • ini_​get_​all
    • ini_​get
    • ini_​parse_​quantity
    • ini_​restore
    • ini_​set
    • memory_​get_​peak_​usage
    • memory_​get_​usage
    • memory_​reset_​peak_​usage
    • php_​ini_​loaded_​file
    • php_​ini_​scanned_​files
    • php_​sapi_​name
    • php_​uname
    • phpcredits
    • phpinfo
    • phpversion
    • putenv
    • set_​include_​path
    • set_​time_​limit
    • sys_​get_​temp_​dir
    • version_​compare
    • zend_​thread_​id
    • zend_​version
    • get_​magic_​quotes_​gpc
    • get_​magic_​quotes_​runtime
    • restore_​include_​path

    Источник

    Php load dll files

    On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

    To load an extension, you need to have it available as a «.dll» file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

    To compile an extension into PHP, please refer to building from source documentation.

    To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

    Where to find an extension?

    PHP extensions are usually called «php_*.dll» (where the star represents the name of the extension) and they are located under the «PHP\ext» folder.

    PHP ships with the extensions most useful to the majority of developers. They are called «core» extensions.

    However, if you need functionality not provided by any core extension, you may still be able to find one in » PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

    If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read » PECL submit.

    Which extension to download?

    • Different version numbers (at least the first two numbers should match)
    • Different thread safety settings
    • Different processor architecture (x86, x64, . )
    • Different debugging settings
    • etc.

    You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

    Example #1 phpinfo() call

    Or from the command line, run:

    Источник

Оцените статью