Install pecl on windows

Установка PECL PHP

Просматривая аналитику обнаружил, что ко мне стали часто обращаться по запросу «установка pecl php», как я понимаю, этому поспособствовала моя предыдущая статья про установку mnoGoSearch. Мне стало интересно, что же люди ищут по этой проблеме?

До конца не осознаю, что их приводит сюда, единственной причиной может служить то, что PECL раздел на официальном сайте PHP долгое время не был переведен на русский язык, может люди ищут русский перевод?

Что-ж, раздел интересный и перевод его занимает не так много времени, людям, которым по душе читать мануалы на русском языке посвящается:

Глава 5. Установка PECL расширений

Таблица содержимого

Введение в PECL установку

PECL это хранилище PHP расширений которое доступно Вам через систему PEAR. Этот раздел руководства предназначет для демонстрации того, как получить и проинсталлировать PECL расширения.

Эти инструкции предполагают, что «/your/phpsrcdir/» это путь к исходному дистрибутиву PHP и что «extname» это имя PECL расширения, поэтому приведите все рассматриваемые здесь примеры в соответствии с Вашими требованиями. Эти инструкции также полагают, что Вы уже знакомы с командой pear.

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

Когда собираются PHP модули, очень важно знать версии всех необходимых инструментов (autoconf, automake, libtool, и т.д.) Смотрите Анонимные CVS инструкции для детализации требуемых инструментов и требуемых версий.

Загрузка PECL расширений

Существует несколько вариантов для загрузки PECL расширений, такие как:

  • http://pecl.php.net

Это веб сайт PECL содержащий информацию о различных расширениях, которые предлагаются командой разработчиков PHP. Информация доступная там содержит: лог изменений, замечания о релизе, требования и другие детали.

pecl download extname

PECL расширение имеющее релизы и находящееся в списке PECL на веб сайте и доступное для скачивания и инсталляции с использованием команды pear. Вами может быть выбрана требуемая ревизия.

Большинство PECL расширений размещено в CVS. Веб просмотр CVS может быть выполнен через http://cvs.php.net/pecl/. Для загрузки прямо из CVS должна быть использована следующая последовательность команд (заметьте, что phpfi это пароль для пользователя cvsread):

Скачивание для Windows

Пользователи Windows могут найти уже скомпилированные PECL файлы выполнив закачку Collection of PECL modules со страницы PHP Downloads и выбрав PECL Snapshot. Для компиляции PHP под Windows, читайте соответствующий раздел.

PECL для Windows пользователей

Как и множество других PHP DLL расширений, инсталляция заключается в простом копировании DLL файла с PECL расширением в папку с расширениями «extension_dir» и их дальнейшей загрузкой в php.ini. Для примера, добавьте следующую строку в Ваш php.ini:

После того, как все сделано, перезапустите веб сервер.

Компиляция совместных PECL расширений с PEAR

PEAR легко создает общедоступные PHP расширения. Используя команду pear, сделайте следующее:

Эта команда загрузит исходник extname, скомпилирует и инсталлирует extname.so в Вашу директорию с расширениями «extension_dir», затем extname.so может быть загружено через php.ini.

По умолчанию, команда pear не инсталлирует пакеты, которые помечены как альфа или бета релизы. Если нет доступного стабильного пакета, Вы можете инсталлировать бета пакет используя следующую команду:

Вы также можете инсталлировать определенную версию расширения используя следующий вариант:

Компиляция совместных PECL расширений с phpize

Иногда использование PEAR инсталлятора невозможно. Такое может быть если Вы находитесь за файерволом или расширение, которое Вы хотите инсталлировать, недоступно Вам как PEAR совместимый пакет, таковыми могут быть неизданные расширения из CVS. Если Вам необходимо построить такое расширение, Вы можете использовать низко-уровневую сборку, выполнив построение вручную.

Читайте также:  Как сбросить astra linux до заводских настроек

Команда phpize используется в качестве подготовки окружения для PHP расширения. В следующем примере исходные коды для расширения находятся в директории названной extname:

Успешная инсталляция создаст файл extname.so и разместит его в директорию с PHP расширениями. Вам необходимо откорректировать php.ini и добавить в него строку extension=extname.so, прежде чем Вы сможете использовать это расширение.

Если в системе отсутствует команда phpize и используются предварительно скомпилированные пакеты (такие как RPM), будьте уверенны в том, что инсталлируете подходящую версию PHP пакета, так как часто они включают в себя команду phpize наряду с предопределенными файлами заголовков для сборки PHP и его расширений.

Выполните phpize —help для показа дополнительной информации об использовании этой команды.

Компиляция статических PECL расширений PHP

Вам может понадобится собрать PECL расширение статически, т.е. прямо непосредственно в код PHP. Для этого Вам необходимо поместить исходный код расширения в директорию «php-src/ext/» и указать сборщику PHP на регенерацию его конфигурационного скрипта.

Это создаст следующую директорию:

Далее дайте PHP команду перестроить конфигурационный скрипт и затем соберите PHP как обычно:

Замечание:
Для запуска скрипта ‘buildconf’ Вам необходимы autoconf 2.13 и automake 1.4+ (более новые версии autoconf могут работать, но не поддерживаться).

В зависимости от расширения используется либо —enable-extname либо —with-extname. Обычно расширение, которое не требует внешних библиотек, использует —enable. Для выяснения этого момента запустите следующую строку после buildconf:

Install pecl on windows

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?

Many times, you will find several versions of each DLL:

  • 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:

Читайте также:  Как активировать kaspersky endpoint security для windows

Installing packages

After getting PEAR working on your machine (see Installation) you most likely want to install some packages. This guide shows people new to the PEAR command line installer how to get started.

Normal installation procedure

The general command to install a PEAR package named «foo» is

Typing this and pressing return, the package will be downloaded and installed on your computer. It does not matter if you write the package name in lowercase, UPPERCASE or MixedCase — the installer will find the package by lowercasing the name.

When a package is already installed, you will get the following message:

This happens even if there is a newer version of the package! The correct command to upgrade to the lastest version is

If the package already has the lastest version, you will get a message similar to the following:

In the case you deleted some file and really really want to re-install the package, you have two choices:

Uninstall the package, and reinstall it afterwards

Force the installation

Forcing an command should only be done when you absolutely know what you are doing — you might in some circumstances break PEAR otherwise. Forcing something should always be the last option.

Unstable alpha/beta packages

Now and then, you will get error messages like

Reason for this is that PEAR by default installs stable packages only. When a package is in state devel, alpha or beta it will refuse to install them. You can easily persuade it by adding either the version number or the stability you are willing to accept:

You can also install a specific version, or upgrade to a specific version regardless of the state:

Living on the edge

If you don’t care about stability and don’t want to specify the -alpha or -beta suffix everytime, you can change the global stability config option:

You can switch between the following stability states (sorted by stability):

Dependencies

A package often requires other packages to be installed to function correctly. Such a relation is called a dependency. The PEAR installer has full support for dependencies; it can automatically install required and/or optional dependencies if you wish so.

If you try to install a package with required dependencies, you will get an error that the installation failed. Looking deeper and actually reading the messages shows you that the package needs dependencies that are not installed on your system:

You have several choices:

Install dependent packages by hand

Let PEAR automatically install necessary dependencies only

Let PEAR automatically install necessary and optional dependencies

The first method can be a painful and daunting process, because dependent packages itself can have dependencies.

Both other methods just require a switch to the install command, either —onlyreqdeps (install required dependencies only) or —alldeps (install all dependencies).

Offline installation

You can download individual packages for e.g. offline installation on a second machine just as you would install or upgrade a package:

After downloading, you will have a file like Foo-1.2.3.tgz if the latest version of Foo was 1.2.3 . Installing it is as easy as typing

Manual package installation

We removed this section, because, today, manually installing a package requires a deeper understanding of the way how packages are organized and what happens during the installation process. You should read the section about the package.xml in the Developers Guide (package.xml and package.xml 2.0), if you really want install a package without the PEAR installer.

If you want to install PEAR on a remote host without shell access, you should look into Installation of a local PEAR copy on a shared host.

Читайте также:  Live usb encrypted persistence kali linux

Installing packages from SVN

This passage will describe how to install the latest development version of a PEAR package from SVN.

It is NOT recommended to run a package from SVN in working environments! Because SVN versions are not regular releases, this means:

  • You could get no kind of help from the maintainer or anybody other.
  • Versions in SVN may break the upgrade mechanism of the PEAR Installer.

You should use a package from SVN only, if:

  • The maintainer recommended it for you.
  • You want to help in development of a package.
  • You really need a special patch or function, which is not currently released.

If you still want to install a package from SVN, you have to do the same steps like a package maintainer creating a new release of a package. If you have problems following the next steps, take a look into the Developers Section of the manual.

Get the package files from SVN like described in http://www.php.net/svn.php

The name of the module to checkout is pear/

/trunk , i.e. svn checkout http://svn.php.net/repository/pear/packages/HTTP_Client/trunk HTTP_Client.

Check the package.xml file, especially the dir and file entries. They must match the existing files and directory structure. If they differ, contact the package maintainer and ask for an update of the package.xml .

Create a valid package using the PEAR Installer pear package

If you have already installed the package: remove it to avoid version conflicts: pear uninstall

Install your package archive: pear install

Now, you have a SVN version installed!

You should upgrade to an official release of the package as early as possible. Before you install the official release, uninstall the SVN version to avoid version conflicts.

Installing PECL packages

The procedure of installing PECL packages is described in the pecl manual section on the PHP website.

Установка расширений 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 , и данные расширения требуют отдельной загрузки.

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