Php install extensions windows

Установка 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.

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

Очень часто существует несколько версий расширения DLL:

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

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

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

Установка расширений PHP в ОС Windows

После установки PHP и веб-сервера на ОС Windows может понадобиться установить некоторые расширения для добавления функционала. Вы можете выбрать, какие расширения будут загружаться при старте PHP, модификацией вашего файла php.ini . Также вы можете загружать расширения динамически в ваших скриптах, используя функцию dl() .

Библиотеки DLL расширений PHP имеют префикс php_.

Многие расширения встроены в Windows-версию PHP. Это значит, что дополнительные DLL-файлы и директива extension не используются для загрузки данных расширений. Таблица расширений PHP в Windows, содержащая список расширений, требующих (или обычно требующих) дополнительные DLL-файлы. Ниже приведен список встроенных расширений (обновлено PHP 5.0.4): BCMath, Caledar, COM, Ctype, DOM, FTP, LibXML, Iconv, ODBC, PCRE, Session, SimpleXML, SPL, SQLite, WDDX, XML и Zlib.

Место по умолчанию, в котором PHP ищет расширения — C:\php5 . Для изменения данной настройки согласно вашей установке PHP отредактируйте файл php.ini следующим образом:

измените опцию extension_dir так, чтобы она указывала на директорию, в которой расположены расширения или в которую вы поместили файлы php_*.dll . Например:

Включите одно или несколько расширений, которые вы хотите использовать, раскомментировав в файле php.ini строки вида extension=php_*.dll. Это делается удалением символа «;» в начале строки для каждого расширения, которое вы хотите включить.

Пример #1 Включение расширения Bzip2 в PHP-Windows

Некоторые расширения для своей работы требуют дополнительные библиотеки DLL. Несколько из них находятся в распространяемом дистрибутиве PHP, в в корневой директории, но некоторые расширения, например, Oracle ( php_oci8.dll ), требуют наличия библиотек DLL, не включаемых в дистрибутив PHP. Не забудьте включить директорию C:\php в системную переменную PATH (данный процесс описан в отдельном разделе помощи).

Некоторые из этих библиотек DLL не поставляются в дистрибутиве PHP. За деталями обратитесь к странице документации конкретного расширения. Также прочтите раздел руководства Установка расширений PECL, чтобы узнать дополнительную информацию о PECL . Все большее число расширений PHP можно найти в PECL , и данные расширения требуют отдельной загрузки.

Как установить расширение PHP: из репозитория и исходников

В большинстве случаев расширение можно установить из репозитория. В репозитории включаются все популярные расширения.

Читайте также:  Длина имени файлов windows может быть

Выяснить, что доступно для установки можно так:

php7.0-mbstring — MBSTRING module for PHP
php7.0-mcrypt — libmcrypt module for PHP
php7.0-mysql — MySQL module for PHP
php7.0-odbc — ODBC module for PHP
php7.0-opcache — Zend OpCache module for PHP
php7.0-pgsql — PostgreSQL module for PHP
php7.0-phpdbg — server-side, HTML-embedded scripting language (PHPDBG binary)
php7.0-pspell — pspell module for PHP

Производится поиск по маске, среди результатов непосредственно php7.0 и все расширения.

Так, если планируется работа с PostgreSQL, то нужно установить php7.0-pgsql.

Любая установка — потенциально опасная операция, поэтому сначала ее следует проводить с ключем —dry-run. В этом случае будут проверены зависимости, но изменений в систему фактически не вносится.

Если ошибок не возникло, но расширение можно устанавливать

Теперь расширение php7.0-pgsql установлено, осталось его подключить.

Сборка расширений PHP

Сборку можно выполнять на рабочей машине, но лучше использовать для этого другой сервер с аналогичной конфигурацией.

Компиляция нужна для расширений, отсутствующих в репозитрии и встречающихся реже.

Исходники расширений можно найти на сайте https://pecl.php.net/

Допустим, что требуется stomp (https://pecl.php.net/package/stomp)

Нужно скачать исходники

Затем распаковать архив

И перейти в каталог с файлами расширения

Далее при условии, что на сервере используется одна версия PHP:

Configuring for:
PHP Api Version: 20100412
Zend Module Api No: 20100412
Zend Extension Api No: 20100412

Если больше одной версии — потребуется указывать phpize под конкретную версию и phpconfig. Это бинарные файлы, использующиеся для сборки.

Ошибки в логах после сборки появляются про разные версии PHP Api Version и Zend Extension Api No говорят о не тех использованных phpize и phpconfig.

При отсутствии phpize устанавливается пакет php5-dev

configure: creating ./config.status
config.status: creating config.h
config.status: executing libtool commands

Build complete.
Don’t forget to run ‘make test’.

Installing shared extensions: /usr/lib/php7.1.21/20160303/

В результате получаем файл /usr/lib/php7.1.21/20160303/stomp.so, который нужно подключить в php.ini

При условии, что используется php той версии, для которой собрано расширение и конфигурационный файл размещается по пути /etc/php/php.ini:

Далее все процессы можно завершить, чтобы быстрее увидеть результат

Php install extensions windows

After installing PHP and a webserver on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini . You can also load a module dynamically in your script using dl() .

The DLLs for PHP extensions are prefixed with php_ .

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini . This is done by deleting the leading ; from the extension you want to load.

// change the following line from . ;extension=php_bz2.dll // . to extension=php_bz2.dll

Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle ( php_oci8.dll ) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don’t forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry ).

Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL . An increasingly large number of PHP extensions are found in PECL , and these extensions require a separate download .

Note: If you are running a server module version of PHP remember to restart your webserver to reflect your changes to php.ini .

The following table describes some of the extensions available and required additional dlls.

Installation on Windows systems

Table of Contents

Installing PHP on modern Microsoft Windows systems and recommended configuration with common web servers.

If you are looking for information about older systems, such as Windows XP, 2003, 98 or Apache 1.x, see the Legacy Info section.

The Official releases of PHP on Windows are recommended for production use. However, you are welcome to build PHP from Source. You will need a Visual Studio environment. See » Step by Step Build Instructions.

Installing PHP on Azure App Services (aka Microsoft Azure, Windows Azure, or (Windows) Azure Web Apps).

User Contributed Notes 12 notes

If you make changes to your PHP.ini file, consider the following.

(I’m running IIS5 on W2K server. I don’t know about 2K3)

PHP will not «take» the changes until the webserver is restarted, and that doesn’t mean through the MMC. Usually folks just reboot. But you can also use the following commands, for a much faster «turnaround». At a command line prompt, type:

and that will stop the webserver service. Then type:

net start w3svc

and that will start the webserver service again. MUCH faster than a reboot, and you can check your changes faster as a result with the old:

in your page somewhere.

I wish I could remember where I read this tip; it isn’t anything I came up with.

You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I’ve seen so far, limited to reconfiguring Apache’s httpd.conf.

My goal is to have PHP5 as the default scripting language for .php files in my DocumentRoot (which is in my case d:/htdocs), and PHP4 for specified DocumentRoot subdirectories.

Here it is (Apache’s httpd.conf contents):

—————————
# replace with your PHP4 directory
ScriptAlias /php4/ «c:/usr/php4/»
# replace with your PHP5 directory
ScriptAlias /php5/ «c:/usr/php5/»

AddType application/x-httpd-php .php
Action application/x-httpd-php «/php5/php-cgi.exe»

# populate this for every directory with PHP4 code

Action application/x-httpd-php «/php4/php.exe»
# directory where your PHP4 php.ini file is located at
SetEnv PHPRC «c:/usr/php4»

# remember to put this section below the above

# directory where your PHP5 php.ini file is located at
SetEnv PHPRC «c:/usr/php5»

—————————

This solution is not limited to having only two parallel versions of PHP. You can play with httpd.conf contents to have as many PHP versions configured as you want.
You can also use multiple php.ini configuration files for the same PHP version (but for different DocumentRoot subfolders), which might be useful in some cases.

Remember to put your php.ini files in directories specified in lines «SetEnv PHPRC. «, and make sure that there’s no php.ini files in other directories (such as c:\windows in Windows).

And finally, as you can see, I run PHP in CGI mode. This has its advantages and limitations. If you have to run PHP as Apache module, then. sorry — you have to use other solution (the best advice as always is: Google it!).

Hope this helps someone.

If you are installing PHP on Vista just go to David Wang’s blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx

I made the mistake of setting a ‘wildcard application map’ for PHP on a Windows 2003 / IIS 6.0 / PHP ISAPI installation.

This resulted in «No input file specified» errors whenever I tried to load the default page in my site’s directories. I don’t know why this broke things, but it did.

If anyone has the same problem, this may be the cause.

IIS setup: 403 forbidden error.

We had installed two separate different PHP versions — PHP 5.1.4 followed by 5.2.5.

We configured 5.2.5 php5isapi.dll to be loaded as the .php file type extension.

Despite this, php version 5.1.4 was being loaded. We renamed 5.1.4’s folder and then PHP was not loading at all.

There were no visible references to 5.1.4 in the IIS configuration, but in the file \webConfig.xml, there was a reference to 5.1.4’s isapi under IISFilters.

To fix this problem, we added version 5.2.5’s php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.

I installed by Microsoft Installer, manually, whatever I always received de same error from IIS7.

HTTP Error 404.3 — Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The IIS7 interface is quite diferent and are not all together like IIS6

The 5.3 version have not any of those files: php5stdll, php5isapi.dll. etc.

The installer puts others files in handlers and I decided to use them as substitutes. Nothing done!

After that, I discovered that installer do not install these files within the sites, but in the root default site configuration of IIS7.

So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)

If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN

There is a .ini file there that prevents some files from being served by IIS, even if they exist, instead IIS will give a 404. The urlscan logfile (same place) should give you some insight into what parameter is preventing a page from loading, if any.

Here’s how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:

1. Right-click My Computer, go to Advanced tab, and click on Environment Variables.

Add the two installations and their EXT directories to the Path variable. For example, add:
c:\php;c:\php\ext;c:\TMAS\php;c:\tmas\php\ext;

Then, add the newer PHP version’s directory as a variable called PHPRC. For example:
Variable:PHPRC
Value: C:\PHP

Click OK to close the Environment Variables window, and click OK to close System Properties.

2. In registry, under HKEY_LOCAL_MACHINE>SOFTWARE>PHP, add a REG_SZ key called iniFilePath and give it a value
of the directory where the older PHP is installed. For example:
C:\TMAS\PHP

3. In IIS, go to the Web Service Extensions. Add both versions’ ISAPI module separately to the extensions
list, and allow both.

4. In IIS, go to each website utilizing the PHP versions. Set an ISAPI filter if needed. On the Home Directory
tab, click Configuration, and add .php, .php3, .phtml, and any other extensions needed (perhaps .html?) to
be filtered through PHP, and specify the ISAPI module version needed for each website.

You can now run two versions of PHP. This is because the order of where to look for the .ini file changed
between previous PHP versions and PHP 5.2, as documented at http://us2.php.net/ini:

* SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
* The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
* HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
* Current working directory (for CLI)
* The web server’s directory (for SAPI modules), or directory of PHP (otherwise in Windows)
* Windows directory (C:\windows or C:\winnt) (for Windows), or —with-config-file-path compile time option
—————————————————-

PHP 5.2.9.2 Install on XP Pro IIS 5.1 — phpinfo( ) results incorrect

Testing Date: 05.15.09

Background:
For several days now I, as a newbie, have been unsure if I had installed PHP correctly, or not. No matter what I did phpinfo( ) reported «Configuratin File Path» as: “C:\WINDOWS”. I was left to wonder what was wrong.

To help resolve the phpinfo() “issue”, I conducted a series of tests using two scripts:

The first is “test-php-ini-loaded.php”; it is stored in c:\inetpub\wwwroot, and has the following code:

if ( $inipath ) <
echo ‘Loaded php.ini: ‘ . $inipath ;
> else <
echo ‘A php.ini file is not loaded’ ;
>
?>

The second script is simply calls phpinfo( ). It is named test.php, is stored in “c:\inetpub\wwroot”, and has the following code:

( ); ?>

My Dev Environment:
1. Windows XP Pro SP3
2. IIS 5.1 / MMC 3.0
3. PHP 5.2.9.2 – phpMyAdmin not yet installed
4. (plus MySQL 5.1, etc.)
5. Install location is on my local E: drive

Читайте также:  Оболочка windows для андроида
Оцените статью