Apache load php files
Этот раздел описывает установку PHP c Apache 2.x на Unix системах.
Мы не рекомендуем использовать потоковый MPM в промышленной среде вместе с Apache 2. Вместо этого, используйте prefork MPM, используемый по умолчанию в Apache 2.0 и 2.2. Подробную информацию по этому вопросу вы можете найти в соответствующем разделе FAQ Apache2 и потоковый MPM
Самым авторитетным источником информации по Apache 2.x является » документация Apache. Более подробная информация о настройках при установке может быть найдена там.
Самая последняя версия Apache Http Server может быть получена на » странице загрузки Apache, а адрес соответствующей версии PHP был указан выше. Это краткое руководство описывает лишь базовую установку Apache 2.x и PHP. Для получения более детальной информации прочитайте » документацию Apache. В инструкции ниже опущены номера версий — замените ‘NN’ на номер, соответствующий скачанной вами версии Apache.
На данный момент есть две версии Apache 2.x — 2.4 и 2.2. Хотя для выбора каждой из них существуют отдельные доводы, 2.4 является наиболее свежей и рекомендуемой версией, если вас устраивает такой выбор. Тем не менее, данные инструкции будут работать как для 2.4, так и для 2.2. Обратите внимание, что Apache httpd 2.2 официально больше не поддерживается, поэтому дальнейшая разработка не будет продолжаться, также как и приниматься новые патчи.
- Скачайте Apache HTTP server как было указано выше и распакуйте его:
cd httpd-2_x_NN ./configure --enable-so make make install
/usr/local/apache2/bin/apachectl start
/usr/local/apache2/bin/apachectl stop
cd ../php-NN ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql make make install
cp php.ini-development /usr/local/lib/php.ini
LoadModule php_module modules/libphp.so
LoadModule php7_module modules/libphp7.so
SetHandler application/x-httpd-php
Или, если мы хотим добавить расширения .php, .php2, .php3, .php4, .php5, .php6 и .phtml, это можно записать так:
SetHandler application/x-httpd-php
Чтобы PHP отображал содержимое файлов .phps с подсветкой синтаксиса, нужно внести соответствующую директиву
SetHandler application/x-httpd-php-source
Можно использовать mod_rewrite для отображения любого .php файла с подсветкой синтаксиса, без нужды его переименования в .phps:
RewriteEngine On RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]
/usr/local/apache2/bin/apachectl start
Если вы следовали инструкциям выше, то на данном этапе должны иметь запущенный веб-сервер Apache2 с поддержкой PHP, как модуля SAPI . Конечно, для PHP и Apache доступно гораздо больше параметров конфигурации. Используйте ./configure —help в соответствующей папке с исходными кодами для получения полного списка параметров конфигурации.
Если вы хотите собрать многопоточную версию Apache, то при сборке вам следует указать модуль MPM worker вместо стандартного модуля MPM prefork . Чтобы сделать это, нужно добавить следующий аргумент к ./configure на шаге 3:
Не следует бездумно использовать эту настройку, используйте её только если вы понимаете все последствия этого решения. Документация Apache по » модулям MPM значительно глубже раскрывает эту тему.
Замечание:
Если вы хотите использовать зависимый контент (content negotiation), прочитайте Apache MultiViews FAQ.
Замечание:
Для сборки многопоточной версии Apache, ваша система должна поддерживать потоки. Это так же подразумевает сборку PHP c поддержкой Zend Thread Safety (ZTS). И, как следствие, не все модули PHP смогут работать. Рекомендуется установка Apache с модулем MPM по умолчанию — prefork .
User Contributed Notes 16 notes
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:
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.
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:
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:
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:
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.
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
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.
Local php.ini Settings aren’t Working or Loading in Apache
DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.
Recently while working for a client’s web host, I had the trouble that local php.ini changes weren’t taking effect. I had already created a custom php.ini file in the user’s home directory and set rules. But these local php.ini settings were not working at all.
Apache server wasn’t loading the php.ini configuration file for the user. As a result, the settings were completely ignored. I’ve managed to fix that. If you have the same trouble then here I will tell you how to rectify this.
The Order of Loading php.ini Settings
First of all, you have to identify the working php.ini settings including the local one. In this step by step tutorial, we will first identify which PHP configuration files are loading. By default, PHP directives take effects in the following order.
- Global or root’s php.ini file that comes with the installed PHP version
- A file set up by the server control panel software
- The custom configuration in the user’s home directory
- Local file in the domain’s document root
- In the same directory where the PHP file resides
- Using the ini_set() function at runtime
So here you see that any directive defined in the later file can override the same from the former one. However, there might be multiple PHP versions installed in your hosting account. Further, you might have the capability to specify PHP executable version per domain or website. Refer to this article to know the two ways to perform the same.
Thus it’s better to know which local as well as master PHP settings files are taking effect. It will also help us to create correct and working configuration files.
Identifying the Effective PHP Configuration Files
It’s time to write and run a line of code. Write phpinfo(); in a PHP file and access this file in the browser. You will come up with the information about Apache and PHP in your system.
The Local Value column displays values from the user’s ini file while Master Values contains values form the global file. Further, the local value displays one from the master if it doesn’t exist in the custom one.
Since Apache is ignoring our PHP ini settings, let us first look at configuration path and loaded files. Search for rows “Configuration File (php.ini) Path” as well as “Loaded Configuration File”. The first one is the file that came with Apache and PHP. While your control panel software (cPanel, Plesk) loads its own php.ini file as shown in the second term.
So you have gotten the file. You can change the necessary directives in the loaded configuration file if have access to it. Otherwise, we should try to load the local php.ini file. Also, not sure but the loaded configuration file might change in the future with updates as well.
Making Local php.ini Settings Working in Apache
Well! It’s not always the php.ini file that loads. PHP has the setting to rename the user-defined configuration file. Look for the directive “user_ini.filename” on the PHP information page in the browser.
Instead of “php.ini”, there might be “.user.ini” provided. it means PHP will look for custom configuration in files named as “.user.ini”. So either you rename local php.ini to .user.ini or set “user_ini.filename” directive to “php.ini”.
Now Apache will load user-specific local ini file for PHP. You can verify the same by reloading PHP information on the browser. Just remember to delete phpinfo(); function or the file from your hosting account afterward.
Additionally, give attention to “user_ini.cache_ttl” directive as well. PHP caches the configuration and avoids re-reading until the cache expires. The value is measured in seconds. 300 seconds means 5 minutes. So either wait or reboot Apache if immediate changes don’t work.
Changing Local or User php.ini to Take Effect
So You have come to know why were PHP settings ignored. Now the local php.ini settings started working after changing the file name. PHP information and configuration are quite helpful utility. I have almost modified more than 25 directives to let Apache and PHP effectively work.
For example, “extension_dir” is one such useful directive. I have set up the PHP extension for Redis using this. Finally, hope you have fixed local php.ini settings aren’t working issue in Apache. If this article is helpful then don’t forget sharing and commenting.