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

search for in the

Apache 2.0 на Unix системах> <Общие инструкции по установке
Last updated: Fri, 28 Nov 2008

view this page in

Установка на Unix системы

Содержание

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

Как сказано в разделе Общие указания по установке, в этом разделе в основном мы описываем установку PHP ориентированную на веб, однако мы так же затрагиваем установку PHP для использования в командной строке.

Есть несколько способов установки PHP на Unix платформы. Один из них - процесс конфигурирования и компиляции исходников, другой - установка из пакетов. Этот документ сфокусирован на установке из исходных кодов. При установке из пакетов, PHP устанавливается в стандартной конфигурации. Если вам нужны особые параметры, то лучше скомпилировать PHP вручную с необходимой конфигурацией.

Для компиляции PHP из исходных кодов вам потребуется следующее:

  • Базовые знания Unix (способность обращаться с "make" и компилятором C)
  • Компилятор ANSI C
  • flex: Version 2.5.4
  • bison: Version 1.28 (предпочтительно), 1.35, или 1.75
  • Веб-сервер
  • А так же библиотеки, требуемые для некоторых модулей PHP (gd, pdf libs и т.д.)

Общая (или начальная) конфигурация PHP задается параметрами скрипта configure. Вы можете просмотреть список допустимых параметров при помощи команды ./configure --help. Так же список основных параметров можно просмотреть в приложении Основные параметры конфигурации, а параметры специфичные для различных расширений описаны на страницах документации, посвященных этим расширениям.

Когда PHP сконфигурирован, все готово к сборке модулей и/или исполняемых файлов. Об этом должна позаботится команда make. Если что-то не получилось и вы не можете понять почему, смотрите раздел Проблемы установки.

Apache 1.3.x на системах Unix

Этот раздел включает иструкции по установке Apache и PHP на платформах Unix. Установка PHP с Apache2 описана в другом разделе.

Вы можете менять аргументы configure на шаге 10 ниже. Полный список аргументов доступен на странице список основных параметров конфигурации. А параметры специфичные для различных расширений описаны в разделах посвященных соответсвующим расширениям. В инструкции ниже опущены номера версий - вы должны заменить 'xxx' на номер версии присутствующий в именах скачанных вами файлов.

Пример #1 Инструкция по установке PHP, как подгружаемого модуля Apache

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Теперь мы сконфигурируем PHP. Здесь вы можете настроить установку
     PHP при помощи параметров скрипта configure.
     Вы можете включить или выключить некоторые расширения. Просмотрите вывод
     команды ./configure --help для получения полного списка параметров
     конфигурации. В нашем примере мы сконфигурируем PHP очень просто -
     с поддержкой Apache и MySQL. В вашей системе путь до apxs может
     отличаться от указанного в примере.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

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

    Заметьте, что 'make install' установит так же PEAR,
    различные инструменты PHP - такие как phpize, версию PHP для командной
    строки (PHP CLI) и т.д.


13. Настройка вашего php.ini

    cp php.ini-dist /usr/local/lib/php.ini

    Вероятно, вы захотите изменить некоторые настройки в php.ini.
    Если вы предпочитаете держать файл php.ini в другом месте, используйте
    параметр --with-config-file-path=/some/path в шаге 10. Если вы используете
    php.ini-recomended, прочитайте его, чтобы знать какие изменения в
    поведении PHP это повлечет.

14. Отредактируйте ваш httpd.conf, чтобы Apache подгружал модуль PHP. Путь в
    инструкции LoadModule должен указывать на модуль PHP. Команда make
    install может добавить эту иструкцию автоматически, но этого может и не
    произойти, поэтому проверьте, чтобы убедиться.

    Для PHP 4:

      LoadModule php4_module modules/libphp4.so

    Для PHP 5:

      LoadModule php5_module modules/libphp5.so

15. Так же в секции AddModule файла httpd.conf, несколько ниже
    ClearModuleList, добавьте следующее:
    
    Для PHP 4:
    
      AddModule mod_php4.c
      
    Для PHP 5:
    
      AddModule mod_php5.c

16.  Теперь следует сконфигурировать Apache, чтобы он передавал файлы с
    некоторыми расширениями на обработку модулю PHP. В нашем примере сделаем
    это для файлов с расширениями .php и .phtml. Вы можете добавить также
    другие расширения в конец строки, разделяя их символом пробела.

      AddType application/x-httpd-php .php .phtml

    Сделаем то же самое для расширения .phps - модуль PHP покажет его как
    исходный код с подсветкой синтаксиса, вместо того чтобы исполнять.

      AddType application/x-httpd-php-source .phps


17. Используйте стандартную процедуру запуска сервера. (Нужно остановить
    и заново запустить сервер, процедура перезапуска с использованием сигналов
    HUP или USR1 в данном случае не подходит.)

В качестве альтернативы, можно установить PHP, как статический модуль Apache:

Пример #2 Инструкция по статической сборке PHP и Apache

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (Строка выше корректна. Да, мы знаем, что libphp5.a не существует на
    данном этапе. Этот файл будет создан.)

12. make
    (Теперь вы должны получить бинарный файл httpd, который вы можете скопировать
    в каталог bin сервера Apache. Затем вам надо выполнить "make install", 
    если это ваша первая установка)

13. cd ../php-5.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. Для изменения конфигурации PHP можно отредактировать файл /usr/local/lib/php.ini.
    Отредактируйте httpd.conf или srm.conf, добавив туда:
    AddType application/x-httpd-php .php

Замечание: Замените php-5 на php-4 и php5 на php4, если вы устанавливаете 4-ю версию PHP.

В зависимости от варианта вашей установки Apache и версии Unix, возможно множество путей остановки и запуска сервера. Ниже приведены несколько распространенных команд перезапуска сервера для различных установок Apache и Unix-систем. Замените /path/to/ на реальный путь до приложений в вашей системе.

Пример #3 Примеры команд перезапуска Apache

1. Некоторые дистрибутивы Linux и системы SysV:
/etc/rc.d/init.d/httpd restart

2. Использование скрипта apachectl:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl и httpsdctl (Использующий OpenSSL), аналогично apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Использующий mod_ssl или другие варианты SSL сервер:
/path/to/apachectl stop
/path/to/apachectl startssl

Пути к apachectl и http(s)dctl часто различаются. Если в вашей системе есть команды locate или whereis, или which, они помогут вам найти программы, контролирующие сервер.

Другие варианты компиляции PHP для Apache:

./configure --with-apxs --with-pgsql

Будет создан файл подгружаемой библиотеки libphp5.so (или libphp4.so для PHP 4). Эта библиотека должна быть подгружена в Apache с использованием директивы LoadModule конфигурационного файла httpd.conf. В данном случае поддержка PostgreSQL будет встроена в эту библиотеку.

./configure --with-apxs --with-pgsql=shared

Будет создан файл подгружаемой библиотеки libphp5.so для Apache, но так же будет создана подгружаемая библиотека pgsql.so, которая должна быть подгружена в PHP одним из двух способов: директивой extension в php.ini или в скрипте, использованием функции dl().

./configure --with-apache=/path/to/apache_source --with-pgsql

Будет создана библиотека libmodphp5.a. Файл mod_php5.c и несколько сопровождающих файлов будут скопированы в каталог src/modules/php5 дерева исходных кодов Apache. Затем следует cкомпилировать Apache, используя --activate-module=src/modules/php5/libphp5.a, система сборки Apache создаст libphp5.a и статически свяжет с исполняемым httpd. (замените php5 на php4 для PHP 4). Поддержка PostgreSQL будет включена непосредственно в httpd и конечным результатом будет единственный исполняемый файл httpd, включающий все от Apache и все от PHP.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

Так же как и прежде, взамен поддержки PostgreSQL, встроенной непосредственно в финальный исполняемый файл httpd вы получите подгружаемую библиотеку pgsql.so, которую вы должны будете подгрузить в PHP одним из двух способов: php.ini или используя функцию dl().

Выбирая способ установки PHP, следует учитывать преимущества и недостатки каждого из методов. Если вы собираете PHP, как подгружаемый модуль Apache - вы сможете компилировать PHP и Apache отдельно друг от друга и вам не нужно будет перекомпилировать Apache, если вы захотите изменить конфигурацю PHP. Если вы собираете PHP статически - PHP будет работать чуть быстрее. Для получения более подробной информаци посетите страницу посвященную поддержке » DSO (Dynamic Shared Object) в Apache.

Замечание: В настоящее время файл конфигурации Apache httpd.conf обычно поставляется со следующими настройками:

User nobody
Group "#-1"
Пока вы не измените группу на "Group nogroup" или что-нибудь вроде "Group daemon" (такая настройка довольно распространена), PHP не сможет открывать файлы.

Замечание: Убедитесь, что вы указываете установленную версию apxs, когда используете --with-apxs=/path/to/apxs. Вы НЕ ДОЛЖНЫ указывать версию apxs, поставляемую с исходными кодами Apache - только действительно установленную в вашу систему вместе с сервером.



add a note add a note User Contributed Notes
Установка на Unix системы
Bobulous
14-Oct-2008 12:53
Notes for anyone trying to get PHP to work with Apache in CGI mode (rather than as a shared module):

http://www.bobulous.org.uk/coding/apache-php-cgi.html

I know that php.net recommends using the more secure shared module mode, but I wanted my development rig to match the setup of my ISP as closely as possible, and my ISP insists they know what they're doing running PHP in CGI mode. (They actually said that CGI was more secure, which I found a bit of a stretch.)

The page is mostly a big, long set of notes for me in case I need to build and configure Apache and PHP in CGI mode again in the future, but I'm hoping that the page may be of use to others too.
Neil Davis
08-Feb-2008 07:51
On Red Hat EL5.1 you need to install the libtool-ltdl-devel package (or the workaround below) to compile php.

symbolic link libltdl.so to libltdl.so.3.1.4 missing and the compile will fail.

Noting this because it wasn't necessary in Red Hat EL4.1 and caused confusion. I verified this on the box I'm migrating from. Since I built the box, and compiled php on it, I know I didn't need to do this before.

You can get around needing to install this devel.
Workaround:
# cd /usr/lib
# ln -s libltdl.so.3.1.4 libltdl.so

The devel rpm isn't necessary, just the link. I'll leave it at that. This is an rpm packaging convention change with ES5.

-Neil
packard_bell_nec at hotmail dot com
27-Oct-2007 04:06
If you install PHP as an Apache module, you can consider the following. Instead of adding:
application/x-httpd-php    php
application/x-httpd-php-source    phps
into Apache mime.types, you can add:
AddType application/x-httpd-php    .php
AddType application/x-httpd-php-source    .phps
into Apache httpd.conf, OR you can add:
AddHandler application/x-httpd-php    .php
AddHandler application/x-httpd-php-source    .phps
into Apache httpd.conf. The last one is the preferred way of configuration, but it does not work in previous Apache versions.
phpnet at puellae dot com
17-Oct-2007 10:19
Further down in the links it talks about using the fPIC option in the compiler to fix the SElinux error.  I messed around with it and adding --with-pic to the configure will also allow the module to load.  I have not done more testing with it but apache at least starts.  If you have already compiled you will need to do a make clean before recompiling.
phpnet at puellae dot com
17-Oct-2007 09:16
If you get an apache failing to start message with SElinux enabled.
The error in var/log/messages is:
Oct 17 10:41:49 nwn kernel: audit(1192635709.825:37936): avc:  denied  { execmod } for  pid=23189 comm="httpd" name="libphp5.so" dev=hda3 ino=4980740 scontext=user_u:system_r:unconfined_t:s0 tcontext=user_u:object_r:usr_t:s0 tclass=file

See the following page:
http://danwalsh.livejournal.com/6117.html?thread=23525

Basically do a chcon -t textrel_shlib_t libphp5.so
It does not sound like it is too dangerous.
aryeh dot friedman at gmail dot com
13-Sep-2007 04:05
For all multi-core processors (not just Sun as noted above) you need to add --enable-shared-core to the apache config
Alex at GrimMusic dot com
13-Nov-2006 12:49
In response to the guy who posted about the SELinux:

I am new to linux/apache/php (coming from server 2003/IIS/Asp.Net), so i was stumped as to why php/apache could only use static content. Also, it couldn't access some documents that you created somewhere else, and then dragged into the HTML directory.

After some research, i found the problem was the SELinux context of the files. It took me forever to find the Proper command to use to change that, as all the examples on the net were out dated using old commands:
# chcon "user_u:object_r:httpd_sys_content_t" /var/www/html -Rc

This will change the SELinux context of all the documents under the /var/www/html directory (which is the web directory under Fedora), to allow the httpd process to access them, and the '-Rc' flag will make the changes Recursive, and will output it's progress for each file that it sucessfully changes.
squeegee
30-Sep-2006 09:24
regarding the note by phptard at gmail dot com:

This was a good starting point to get php built against the Intel-compiled mysql, but in my case, there were still errors. It wasn't until I also added LIBS="-lirc" to the beginning of the configure line that it would configure without errors. It also compiled fine after that. So the start of my configure line looked like this:

LDFLAGS="-lirc" LIBS="-lirc" EXTRA_LIBS="-lirc" ./configure
Arjan van Bentem
12-Jul-2006 12:29
When using Red Hat Fedora, beware of Security Enhanced Linux, SELinux.

Quoted from Red Hat: "The security goal is to make sure that Apache HTTP is only reading the static Web content, and not doing anything else such as writing to the content, connecting to database sockets, reading user home directories, etc."

These limitations include, among many other things, using mkdir to create directories, using fopen to access files, using fopen or get_headers to read URLs, or using exec to run external applications that happen to use sockets (or maybe access some files, but which will run fine when executed from the command line as Unix user apache or httpd -- such as HylaFAX "faxstat" as invoked from nweb2fax recvq.php and sendq.php).

See /var/log/messages for any denials due to the SELinux policy. To disable it:

- System, Administration, Security Level and Firewall
- open the SELinux tab
- click the Transition tree
- check Disable SELinux protection for Apache HTTP
- execute /etc/init.d/httpd restart

See also http://fedora.redhat.com/docs/selinux-faq/ and http://php.net/results.php?q=selinux&p=wholesite
flconseil at yahoo dot fr
07-Mar-2006 06:15
Building Apache 2 and PHP 5.1.2 :

On AIX 5.2 : http://flaupretre.free.fr/redir.php?key=build_apa_aix

On HP-UX 11i (11.11) : http://flaupretre.free.fr/redir.php?key=build_apa_hpux

These documents are complete step-by-step howtos, and describe how to buid a self-sufficient package, including every software it depends on (zlib, SSL, LDAP, iconv, expat, xml, xslt, gd, png, Xpm, jpeg, freetype, bzip2, curl, MySQL, PostgreSQL, Oracle, AdoDB).
dpresley4 at yahoo dot com
06-Nov-2005 03:42
Hi,

PROBLEM:  ./configure PHP --with-oci8

fails with unresolved references such as __rpc_thread_destroy@GLIBC_2_2_3_...

ONE SOLUTOIN

FOR SOLVING PHP ./configure RESULTING IN  __rcp_thread_destroy@GLIBC_2_2_3_... AND
UNRESOLVED REFERENCES WITH ORACLE OCI8

KEYWORDS: PHP OCI OCI8 NET8 ./configure __rpc_thred_destroy UNRESOLVED REFERENCES

For building php-4.4.1 or later with oci8, make sure your LD_LIBARRY_PATH has at a minimum the following directories in its path for Oracle8i 8.1.5 or later, Oracle9i 9.0.2 or later, and Oracle9i Release 2: 9.2.0.4 or later, do the following:

Note:  We are not using the Oracle Instant Client here.  This assumes you have an actual Oracle Installation.

1. Set ORACLE_HOME

Example using Oracle 9i Relase 2 -- 9.2.0.5:

ORACLE_HOME=/opt/app/oracle/product/9iR2

2. Set LD_LIBRARY_PATH with:

LD_LIBRARY_PATH=$ORACLE_HOME/lib: \
    $ORACLE_HOME/rdbms/lib:\
    $LD_LIBRARY_PATH

3. On Unix / Linux, don't forget to export these environment variables:

export ORACLE_HOME LD_LIBRARY_PATH

4. Now, build PHP with the following:

./configure --with-apxs2=<path to Apache 2.0/bin/apxs> --with-oci8=$ORACLE_HOME --enable-sigchild

It should now build correctly. The key with Oracle is to ensure that you pick up the libclntX.so (client librariess) where X is the Oracle version associated with the version your using for instance, in the above example, libclnt9.so

Also note that if your using Oracle 9iAS Release 2 v9.0.2, Oracle 10g iAS Release 1 v9.0.4.1, the above steps will work because ORACLE_HOME will containe all of the libraries necessary.  Simply point ORACLE_HOME to the top level directory of these installations and set LD_LIBRARY_PATH as described above.

Hope this helps.
phptard at gmail dot com
23-Mar-2005 04:17
after a long night of wrestling with mysql4.0 under linux compiled with the intel compiler, i've gotten php5.0.3 to compile with mysql libraries for this flavor of mysql:

1: download the mysql for linux/intel compiler and install
2: download the rpm for the intel compiler libraries and install
3: configure php with LDFLAGS="-lirc -lgcc_s" and EXTRA_LIBS="-lirc -lgcc_s"

Example:

LDFLAGS="-lirc -lgcc_s" LD_LIBRARY_PATH="-L/usr/lib64" LD_PATH="-L/usr/lib64" LDPATH="-L/usr/lib64" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-ssl=/usr/local/ssl --without-sqlite --with-zlib-dir=/usr --with-mysql=/usr/local/mysql

of course this is on a xeon system that has half of its modules in the /usr/lib64 directory, so on a normal system, without the other kruft, it would look something more like this:

LDFLAGS="-lirc -lgcc_s" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql

Hopefully this will save someone the 6 hour headache it caused me..
alexander justadot henry at acm dot org
22-Dec-2004 12:48
The system at my workplace has a need for apache/php with all static compilation.  In order to save time adminning our systems, I decided to make my own RPM of php/apache with mod_ssl support.  I had always installed by hand with the instructions on this page, but when buiding the RPM way, came upon the following error when apache was compiling:

===> src/modules/php4
make[4]: *** No rule to make target `all'. Stop.

Ordinarily this is because one did not do a 'make install' in php before the second apache configure, or somehow the make install failed.  But the way rpm's work, the make install must be in the %install portion of the spec file, after all makes are completed.

make install-sapi

This line will copy relevant files to the directory specified in --with-apache
thansen at terra dot com dot br
30-Dec-2003 08:36
The configure directives --with-apxs2 and --with-apxs2filter are not compatible one with other, even though the configure script will not complain about that. Each one affect the way Apache will call the php parser: If you choose the first one, you must use the traditional include:

AddType application/x-httpd-php php

at httpd.conf, to call the parser. If you use the --with-apxs2filter, the include will be:

<Files *.php>
        SetOutputFilter PHP
        SetInputFilter  PHP
</Files>

, and php will be called as a filter to .php files.

If you use both together, you will get compilation errors (duplicate symbols while linking libphp4).
aaronmorris at mindspring dot com
05-Dec-2003 12:47
If you have the libphp4.a instead of libphp4.so on AIX, you can extract the .so file from the .a file by running "ar -x libphp4.a".
jazee_at_bigfoot.com
26-Mar-2003 12:52
http://dan.drydog.com/apache2php.html has a nice set of instructions for Apache2 + php
doug at NOSPAM dot techie dot net
04-Feb-2003 05:16
Users compiling under some versions of Solaris/SunOS may encounter the following error.
   symbol ap_block_alarms: referenced symbol not found

To address this problem, add the following additional flag to the Apache build configure line:
   --enable-rule=SHARED_CORE

So, adding this to the original instructions, you'd configure your Apache build like so:
   ./configure --prefix=/www --enable-module=so --enable-rule=SHARED_CORE

Doug
dimaberastau at hotmail dot com
09-Jun-2001 09:33
when installing with mysql support (--with-mysql=<path/to/your/mysql>) via Apache APXS you'll probably get something like 'can't load libmysqlclient.so' when you try to start up apache. There are 2 solutions to this problem. First, (as documented in INSTALL file of the php4 distribution) you can modify /etc/ld.so.conf to contain the directory name where libmysqlclient.so is (so if your mysql is installed in /usr/local, you want to add something like /usr/local/lib/mysql into /etc/ld.so.conf), else (and particularly if you haven't got the super-user on the system) you can modify (or create if it isn't defined already) LD_LIBRARY_PATH shell variable to reflect the changes you would have otherwise made to /etc/ld.so.conf (again if mysql is /usr/local LD_LIBRARY_PATH=/usr/local/lib/mysql). Either one of these methods will get the problem sorted. Just remember to run ldconfig (so that /etc/ld.so.cache is updated) if you chose to modify /etc/ld.so.conf
marshalm at ebrd dot com
17-May-2001 10:43
HP-UX 11.X PA-RISC installation with oracle (oci8). You need to install the HP-UX patch PHSS_22514 patch (updated libdld.sl), otherwise you will get errors with dlopen() and dlclose() not found during the apache integration stage.

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