Dutch PHP Conference 2025 - Call For Papers

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

Цей розділ містить замітки та підказки щодо встановлення Apache 2.x з PHP в системи Unix.

Увага

Ми не рекомендуємо використовувати потоковий MPM у виробничому середовищі з Apache 2. Замість нього краще обрати prefork MPM, який початково йде з Apache 2.0 та 2.2. Докладніше — у розділі Apache 2 з потоковим MPM

» Документація на сайті Apache є найбільш авторитетним джерелом інформації про сервер Apache 2.x. Там можна знайти більше інформації про параметри його інсталяції.

Найновішу версію HTTP-сервера Apache можна отримати на » сторінці завантаження Apache. Також треба завантажити потрібну версію PHP (див. навігаційну панель вгорі). Тут є лише короткий опис базового встановлення Apache 2.x та PHP. Детальнішу інформацію можна прочитати в » Документації Apache. Зазначення конкретного номера версії навмисно оминається, щоб не плутати користувачів наведених тут інструкцій. Внизу в прикладах, 'NN' потрібно замінити версією Apache, яка буде використовуватись.

На даний момент є дві версії Apache 2.x - це 2.2 та 2.4. Хоча є певні причини для вибору однієї чи іншої версії, але 2.4 є зараз найновішою та рекомендованою. Тим не менш, наведені тут інструкції мають працювати для обох версій. Варто зазначити, що Apache httpd 2.2 офіційно не підтримується і для нього не випускаються нові розробки чи виправлення.

  1. Завантаживши HTTP-сервер Apache, його необхідно розпакувати:

    tar -xzf httpd-2.x.NN.tar.gz
    
  2. Аналогічно, неодхідно розпаковати файли з початковим кодом PHP:

    tar -xzf php-NN.tar.gz
    
  3. Далі потрібно зібрати та встановити Apache. Докладніші рекоментації є на сайті Apache.

    cd httpd-2_x_NN
    ./configure --enable-so
    make
    make install
    
  4. Тепер Apache 2.x.NN доступний за адресою /usr/local/apache2, зі встановленим стандартним модулем MPM prefork та конфігурацією, яка дозволяє додавати інші потрібні модулі. Щоб перевірити інсталяцію, використовується звичайна процедура для старту сервера Apache, наприклад:

    /usr/local/apache2/bin/apachectl start
    
    далі треба зупинити сервер, щоб перейти до встановлення PHP:
    /usr/local/apache2/bin/apachectl stop
    

  5. Тепер конфігуруємо та збираємо PHP. Наприклад, визначаємо які саме розширення будуть включені в PHP. Щоб побачити список доступних параметрів, запускаємо ./configure --help. В даному прикладі виконується проста конфігурація Apache 2 з підтримкою MySQL.

    Якщо Apache було зібрано вручну, як описано вище, в наступному прикладі шлях буде відповідати розташуванню apxs, але якщо Apache встановлювався по-іншому, то потрібно змінити шлях до apxs. Варто зауважити, що деякі дистрибутиви можуть перейменувати apxs в apxs2.

    cd ../php-NN
    ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql
    make
    make install
    

    Для зміни конфігурації після інсталяції, потрібно запустити заново кроки: configure, make та make install. Після цього перезапустити Apache, щоб зміни були застосовані. Перекомпільовувати Apache не потрібно.

    Варто зауважити, що якщо не сказано іншого, то 'make install' буде також встановлювати PEAR, PHP CLI, певні сервіси PHP, такі як phpize та інше.

  6. Встановлення php.ini.

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

    Можна редагувати файл .ini, додаючи потрібні опції PHP. Для розміщення php.ini в іншому місці, використовується опція --with-config-file-path=/some/path на 5-му кроці.

    Якщо буде обрано php.ini-production, краще прочитати список відмінностей між файлами .ini, щоб розуміти як це вплине на поведінку PHP.

  7. Відредагуємо httpd.conf, щоб завантажувався модуль PHP. Шлях, який зазначено праворуч від запису LoadModule, повинен вказувати на розташування модуля PHP у системі. Команда make install, про яку тут згадувалось раніше, повинна вже була зробити це, але краще перевірити ще раз.

    LoadModule php_module modules/libphp.so

    Для PHP 7:

    LoadModule php7_module modules/libphp7.so
  8. Скажемо Apache, щоб обробляв розширення .php через PHP. Замість того, щоб використовувати лише директиву Apache AddType, ми хочемо уникнути потенційної небезпеки завантаження та створення файлів, таких як exploit.php.jpg, які будуть оброблятись через PHP. Використовуючи цей приклад, можна додати будь-яке закінчення (і не одне), яке буде оброблятись через PHP. Ми вказали .php лише для прикладу.

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    Або ж, якщо ми хочемо дозволити щоб файли .php, .php2, .php3, .php4, .php5, .php6, та .phtml оброблялись через PHP, але ніякі інші, ми пишемо так:

    <FilesMatch "\.ph(p[2-6]?|tml)$">
        SetHandler application/x-httpd-php
    </FilesMatch>

    Або щоб дозволити файли .phps обробляти через php source filter, та показувати їх вміст з підсвічуванням синтаксису, використовується таке:

    <FilesMatch "\.phps$">
        SetHandler application/x-httpd-php-source
    </FilesMatch>

    Можна використовувати модуль mod_rewrite, щоб дозволити показувати початковий код з підсвічуванням синтаксису в файлах з розширенням .php, без необхідності їх переназивати чи копіювати до файлів .phps:

    RewriteEngine On
    RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

    Не слід вмикати php source filter на виробничих системах, де він може розкрити конфіденційну або іншу важливу інформацію, розміщену в початковому коді.

  9. Стандартну процедура запуску сервер Apache:

    /usr/local/apache2/bin/apachectl start
    

    АБО:

    service httpd restart
    

Дотримуючись зазначених вище кроків, ми запустимо вебсервер Apache2 з підтримкою PHP як модуля SAPI. Звичайно, є значно більше параметрів, доступних для Apache та PHP. Більше інформації можна отримати ввівши в консолі ./configure --help в їхніх кореневих теках.

Apache можна зробити багатопотоковим, вибравши worker MPM, замість стандартного prefork MPM під час збирання Apache, додавши наступний параметр до ./configure на 3-му кроці:

--with-mpm=worker

Не варто бездумно використовувати цю опцію, а тільки, якщо відомо про всі наслідки такого рішення. В документації для Apache стосовно » модулів MPM значно детальніше розкрита ця тема.

Зауваження:

У розділі "Часті питання (ЧаПи)" з приводу Apache MultiViews є відповідь, чи можна використовувати цю опцію разом з PHP.

Зауваження:

Щоб зібрати версію багатопотокового Apache, цільова система повинна мати підтримку потоків. В цьому випадку, PHP потрібно також збирати з Zend Thread Safety (ZTS). Цю конфігурацію підтримують не всі розширення. Ми рекомендуємо встановлювати Apache зі стандартним модулем prefork MPM.

add a note

User Contributed Notes 16 notes

up
16
nmmm at nmmm dot nu
15 years ago
When I upgrade to apache 2.2, this:

AddType application/x-httpd-php .php5
AddType application/x-httpd-php .php42
AddType application/x-httpd-php .php4
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtm
AddType application/x-httpd-php .phtml
AddType application/x-httpd-php .asp

...does not worked for me, so I did this:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler application/x-httpd-php
</FilesMatch>

Another interesting point with Apache 2.2 is following.
Let suppose we installed PHP as module. But for some directory, we need to use PHP as CGI (probably because of custom configuration). This can be done using:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action application/x-httpd-php-custom /cgi-bin/php-huge

Note type must be different than "application/x-httpd-php" and also you need to deactivate the handler on sertain extention. You can do mixed configuration:

<FilesMatch "\.(php)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action application/x-httpd-php-custom /cgi-bin/php-huge

in such case files like *.php5 and so on will be parsed via module, but *.php will go to php-huge executable.
up
7
Morning Star
1 year ago
I had just installed php8.1.12 on a machine used for writing C code.

Below are some libraries that I needed to download on a debian-based OS.

apt-get install libpcre3 libpcre3-dev
apt-get install apache2-dev
apt-get install libxml2-dev
apt-get install libsqlite3-dev

These were the missing packages that I required.
If you get an error regarding a missing package or library, for example when I needed sqlite3, run the command:

apt search sqlite3

And you'll be able to see if there's any dev or lib packages.

The apache2 instructions worked flawlessly at the time of php8.1.12; and in order to get certain requirements for an application, I had to run the php configure file like so:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql --with-mysqli --with-zip --enable-gd

The extra flags allowed me to use both types of mysql, allowed me to utilize PHP zip archiving, and allowed me to use Gnatt stuff.
up
8
Tom420.Duhamel
15 years ago
I have successfully installed Apache 2.2.11 and PHP 5.2.8 under Red Hat 9.0 on a Pentium 166 with 32 MB of RAM.

While I used RH9, the worst possible case, these notes are probably good for RH-based distributions too (Red Hat Enterprise, Fedora, CentOS...)

If you want to install MySQL, it needs to be installed before PHP because PHP requires some libraries be available.

One think important when picking up a binary distribution of MySQL is to download all four packages: MySQL-server, MySQL-devel, MySQL-client and MySQL-shared. Note: The MySQL was bundled with PHP 4 but is not anymore in PHP 5.

Then you need to install Apache before PHP, because again PHP needs some libraries be available. I installed Apache 2 from source, using the very last version available, which is 2.2.11.

I installed PHP 5.2.8 from source. Here, I had a number of problems, but none which I could not resolve easily, some of them with a little help from different forums I found through Google.

Rembember: When it says you need a package named xyz and you notice there is also one named xyz-devel, grab it.

Most of the packages I got from:
http://legacy.redhat.com/pub/redhat/linux/9/en/os/i386/RedHat/RPMS/
A similar page exists for other versions of Red Hat
and:
http://rpmfind.net/
This site has an updated version of some of the packages. Make sure to use only the one labeled for you version (in my case, Red Hat 9.0) or it will not likely work.

You already have glibc and glibc-common installed, but you need to get glibc-devel and glibc-kernheaders. Make sure to match glibc's version (rpm -q glibc). Note: When it says kernel-header is a required dependency, that's glibc-kernheader (not kernel-source). You will also need binutils (no need to match the version), and gcc and cpp (version must match).

You need zlib-devel (zlib is probably already installed, match the version you have).

If you install the GD extension, the actual library is already bundled with PHP 5 (use that one, they have done some changes in there, so don't upgrade), but you will need to install libpng and libpng-devel (match version, or disable in configure if you don't want) and libjpeg (no -devel with that one).

You will also need libxml2. Now there were a problem, because PHP requires libxml2 be 2.6 or greater, but Red Hat only supplied 2.5.4-1 for RH9 (if you have a more recent distro, you might be more lucky). After looking for a while, I decided to grab the source code for the most recent distribution at the official website (http://xmlsoft.org/) and compiled.

Hope my post is useful to someone. Please, share your experience when compiling/installing for your particular platform and setup. Remember how hard it's been for you the very first time. I confess, my very first server installation took me nearly a week and I was glad others helped me.
up
7
happyboy at php dot org
19 years ago
FILE TRUNCATED!!

during the make process should u receive an error declaring ext/ctype/ctype.lo (or another file) is truncated then you need to 'make clean' prior to a healthy 'make' and 'make install.'

looking into your ext/ directory you may find the offensive file to be 1 byte long.
up
7
Anonymous
7 years ago
Building php 7.1.3 with mysql 5.7.17 and httpd 2.4.25 on Debian 8, step 5 failed for me. Instead of

--with-mysql

try

--with-pdo-mysql

or

--with-mysqli
up
5
1097625354 at qq dot com
5 years ago
解析PHP,需要Apache 2.4.9 以后
<FilesMatch \.php$>
SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
up
5
felixcca at yahoo dot ca
18 years ago
I've (painfully) discovered that installing PHP5 with "make install" under SuSe 9.2 is NOT a good idea.
http://www.aditus.nu/jpgraph/apache2suse.php
This page explains how to install it without breaking everything that's php-related in the Apache2 configuration. Its first purpose, though, is to show how to have php 4 and 5 to cohabit properly.
up
4
svepa at milestone42 dot com
12 years ago
On 64-bit Fedora systems (I'm using Fedora 14), configuring PHP to use the MySQL libraries installed as part of the distribution gives the following error if you follow the default instructions in this manual.

Cannot find libmysqlclient under /usr

Modifying he following invocation of configure as follows:

./configure --with-apxs2=/path/to/apxs --with-libdir=lib64 --with-mysql

should work.

Note the addition of --with-libdir=lib64
This points the configure script to look for 64-bit mysqlclient libraries.
up
4
praveen dot k at masconit dot com
19 years ago
Hi too had same problem with multiview like when i execute http://huey/admin/test.php it used to compile but when i use http://huey/admin/test it wouldnt recognise it as php file... i worked it out with the addhandler method and AddType in different line and setting multiview for directive

"multiviews Options Indexes FollowSymLinks MultiViews"

the directives u can set it to root directory so now when u type pn test it will search in precendence for test.php, test.html if any .....

its working for me with apache2.0.47 and php 4.3.9 on solaris

praveen
up
2
frank@ethisoft
18 years ago
Using Apache2 & PHP5 work perfectly fine & safe together.
- all core modules are safe in Zend Engine 2
- third-party-libraries should be avoided
- semaphores and shared memory enables you to ensure yourself that your application/website is thread-safe also with non-thread-safe PHP modules!
up
2
Dan Scott (dan dot scott at acm dot org)
19 years ago
Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

SuSE uses a rather fragmented set of Apache configuration files stored in /etc/apache2/. When you configure PHP 5.x with:

$ ./configure --with-apxs2=/usr/sbin/apxs2
$ make

everything builds just fine; but when you issue:
$ su -c "make install"

the unconventional Apache conf file layout confuses the install-sapi section of the Makefile and the process halts with the following error:

apxs:Error: Config file /etc/apache2/httpd2-prefork.conf not found.
make: *** [install-sapi] Error 1

At this point only the PHP SAPI library has been copied into place; the rest of the files (like PEAR scripts, PHP-CLI, etc) have not been installed. But never fear! You can overcome this problem with the following steps:

1. Edit Makefile and change the following line to remove "install-sapi":
install_targets = install-sapi install-cli install-pear install-build install-headers install-programs

2. Issue the make install command again:
$ su -c "make install"

3. Add the PHP module & type instructions to the Apache configuration. As root, create a new file, /etc/apache2/conf.d/php5.conf that contains the following lines:

LoadModule php5_module /usr/lib/apache2/libphp5.so
AddType application/x-httpd-php php

--- And that's it. Everything else is just as the documentation suggests it should be.
up
2
neil
19 years ago
To install mysql and mysqli with PHP5 do the following:

after doing:

./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config

do this:

"
if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"

then you can:

make
make install

.....
Pleasse note: you must have mysql-dev installed (RPM or source) or you will not have the mysql_config file at all. The standard, server, and client installations of MySQL do not include it. I read somewhere that the mysql and mysqli paths must be identical.

Quoted from Michael Kofler at the following link:
http://www.kofler.cc/forum/forumthread.php?rootID=3571
up
2
Anonymous
15 years ago
Solution for fedora is yum install mysql-devel. Then set --with-mysql=/usr/include/mysql/
monguesto
up
2
chris@gerlt -dot- net
17 years ago
Install issues on Redhat, specifically RHEL4 with php4 already installed:

I discovered that there was an issue caused by redhat loading php4 in another file seperate from the httpd.conf file! This took me hours to discover. Make sure you know if the apache config file (httpd.conf) is loading configurations from a directory (or another file(s)) as well. If so, look in there for any php module loading which could conflict with the new module you are compiling/installing.
up
1
dfeprado at gmail dot com
11 months ago
When compiling for an Ubuntu 22.04 + Apache2 HTTPD (the one that comes from the default repo), you can face the following error when starting apache2.service:

"Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP."

So, I came back to PHP source and configured it like this:

$ make clean
$ ./configure [...all your build needs] --enable-zts
$ make
$ sudo make install

Then it worked.
up
-1
susie91
18 years ago
for slackware 10.2 users with apache2, mysql5, and trying to install php5:

when following the directions above, after this step:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

i kept getting this error:
"Unable to find MySql header files...."

the only way i could get php5 with mysql support was to compile MySql5 from source, and not use the binary as the mysql site recommends.

then i was able to ./configure successfully, but for some reason php was configured to compile the CGI version.

so, had to use this ./configure line:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql --disable-cgi

alternatively, you could install php4 which does bundle the MySql client files.
To Top