Установка на Unix-системы
Этот раздел описывает установку и настройку PHP на Unix-системах. Пожалуйста, прочитайте все разделы, касающиеся вашей платформы или веб-сервера, прежде чем вы приступите к установке.
Как сказано в разделе Общие указания по установке, в этом разделе в основном мы описываем установку PHP, ориентированную на веб, однако мы также затрагиваем установку PHP для использования в командной строке.
Есть несколько способов установки PHP на Unix платформы. Один из них — процесс конфигурирования и компиляции исходников, другой — установка из пакетов. Этот документ сфокусирован на установке из исходных кодов. Много Unix-подобных систем имеют различные системы установки программ из пакетов. Они могут помочь при установке стандартных конфигураций, но если вам необходимы другие варианты (такие как безопасный сервер или другой драйвер базы данных), вам может потребоваться скомпилировать PHP и/или ваш веб-сервер. Если вы незнакомы с компилированием собственного программного обеспечения, то, может быть, стоит поискать готовый пакет PHP с нужными вам возможностями, собранный кем-нибудь ещё.
- Базовые знания Unix (способность обращаться с "make" и компилятором C)
- Компилятор ANSI C
- Веб-сервер
- Любые компоненты, специфичные для отдельных модулей PHP (такие как библиотеки GD , PDF и т.д.)
- autoconf: 2.59+ (для PHP >= 7.0.0), 2.64+ (для PHP >= 7.2.0)
- automake: 1.4+
- libtool: 1.4.x+ (кроме версии 1.4.2)
- re2c: 0.13.4+
- bison:
- PHP 7.0 — 7.3: 2.4 и выше (включая Bison 3.x)
- PHP 7.4: > 3.0
Общая (или начальная) конфигурация PHP задаётся параметрами скрипта configure. Вы можете просмотреть список допустимых параметров вместе с их кратким пояснением при помощи команды ./configure —help. Различные опции документированы в данном руководстве отдельно, список основных параметров можно просмотреть в приложении Основные параметры конфигурации, тогда как параметры, специфичные для различных модулей, описаны на страницах документации, посвящённых этим модулям.
Когда PHP сконфигурирован, все готово к сборке модулей и/или исполняемых файлов. Об этом должна позаботиться команда make. Если что-то не получилось и вы не можете понять почему, смотрите раздел Проблемы установки.
Замечание:
Некоторые Unix системы (такие как OpenBSD и SELinux) могут запрещать, из соображений безопасности, выделение памяти одновременно как записываемой и исполняемой. Это называется PaX MPROTECT или нарушение защиты W^X. Тем не менее, такой режим выделения памяти необходим для поддержки JIT компиляции PCRE JIT, так что в таких случаях необходимо собирать PHP без поддержки JIT компиляции PCRE, либо бинарные файлы должны быть внесены в белый список операционной системы,
Замечание: Кросс-компиляция под ARM с помощью "Android toolchain" на данный момент не поддерживается.
Как установить php на linux
Раздел содержит информацию и подсказки, относящиеся к установке PHP на » Debian GNU/Linux.
Неофициальные сборки от третьих лиц не поддерживаются. О любых ошибках следует сообщать разработчикам Debian, но перед этим стоит проверить, возможно они уже исправлены в новых релизах, которые можно скачать на » странице загрузки.
Хотя и существует универсальная инструкция по установке PHP на Unix/Linux, в этом разделе мы рассмотрим особенности специфичные для Debian, такие как использование команд apt или aptitude . В рамках этого руководства обе эти команды рассматриваются как взаимозаменяемые.
Использование APT
Во первых, обратите внимание на то, что некоторые пакеты связаны: libapache-mod-php нужен для интеграции с Apache 2, и php-pear с PEAR.
Во-вторых, перед установкой убедитесь, что список пакетов находится в актуальном состоянии. Как правило, это делается с помощью команды apt update.
Пример #1 Пример установки Apache 2 на Debian
APT автоматически установит модуль PHP для Apache 2 и все их зависимости и, затем, активирует их. Apache должен быть перезапущен для того, чтобы изменения вступили в силу. Например:
Пример #2 Остановка и запуск Apache после установки PHP
Контроль конфигурации
Изначально, PHP устанавливается только с основными модулями ядра. Если вы хотите установить дополнительные модули, такие как MySQL, cURL, GD и т.д., это также можно сделать с помощью команды apt .
Пример #3 Способы получить список дополнительных пакетов PHP
Будет выведен список большого числа пакетов, включая несколько специфичных, таких как php-cgi, php-cli and php-dev. Определите, какие вам нужны и установите с помощью apt-get или aptitude . И, так как Debian производит проверку зависимостей, вам будет выведен запрос на их установку.
Пример #4 Установка PHP с MySQL и cURL
APT автоматически добавит необходимые строки в соответствующие php.ini , /etc/php/7.4/php.ini , /etc/php/7.4/conf.d/*.ini , и т.д. В зависимости от модуля, будут внесены записи типа extension=foo.so . В любом случае, чтобы эти изменения вступили в силу, необходимо будет перезапустить сервер веб-сервер.
Стандартные проблемы
- Если скрипты PHP не разбираются веб-сервером, то скорее всего это означает, что PHP не был добавлен в конфигурацию веб-сервера. На Debian это обычно /etc/apache2/apache2.conf или похожий. Смотрите документацию Debian для выяснения подробностей.
- Модуль, по-видимому, установлен, а его функции всё равно не распознаются. В таком случае убедитесь, что соответствующий ini-файл был загружен и/или веб-сервер был перезагружен после установки модуля.
- Для установки пакетов в Debian существуют две основных команды (не считая стандартных вариантов Linux): apt и aptitude . Объяснения их синтаксиса, особенностей и отличий друг от друга выходит за рамки данного руководства.
User Contributed Notes 6 notes
To refresh this document, perhaps it would be worth mentioning more modern methods to serve php content under apache httpd.
Specifically, the preferred method is now fastcgi, using either of those recipes:
While the legacy mod_php approach is still applicable for some older installations, the fastcgi method is much faster, and require much less RAM to operate, based on similar traffic patterns.
Compiling PHP on Ubuntu boxes.
If you would like to compile PHP from source as opposed to relying on package maintainers, here’s a list of packages, and commands you can run
STEP 1:
sudo apt-get install autoconf build-essential curl libtool \
libssl-dev libcurl4-openssl-dev libxml2-dev libreadline7 \
libreadline-dev libzip-dev libzip4 nginx openssl \
pkg-config zlib1g-devSo you don’t overwrite any existing PHP installs on your system, install PHP in your home directory. Create a directory for the PHP binaries to live
STEP 2:
# download the latest PHP tarball, decompress it, then cd to the new directory.STEP 3:
Configure PHP. Remove any options you don’t need (like MySQL or Postgres (—with-pdo-pgsql))./configure —prefix=$HOME/bin/php-latest \
—enable-mysqlnd \
—with-pdo-mysql \
—with-pdo-mysql=mysqlnd \
—with-pdo-pgsql=/usr/bin/pg_config \
—enable-bcmath \
—enable-fpm \
—with-fpm-user=www-data \
—with-fpm-group=www-data \
—enable-mbstring \
—enable-phpdbg \
—enable-shmop \
—enable-sockets \
—enable-sysvmsg \
—enable-sysvsem \
—enable-sysvshm \
—enable-zip \
—with-libzip=/usr/lib/x86_64-linux-gnu \
—with-zlib \
—with-curl \
—with-pear \
—with-openssl \
—enable-pcntl \
—with-readlineSTEP 4:
compile the binaries by typing: makeIf no errors, install by typing: make install
STEP 5:
Copy the PHP.ini file to the install directory/bin/php-latest/etc;
mv php-fpm.conf.default php-fpm.conf
mv php-fpm.d/www.conf.default php-fpm.d/www.confSTEP 7:
create symbolic links for your for your binary files/bin
ln -s php-latest/bin/php php
ln -s php-latest/bin/php-cgi php-cgi
ln -s php-latest/bin/php-config php-config
ln -s php-latest/bin/phpize phpize
ln -s php-latest/bin/phar.phar phar
ln -s php-latest/bin/pear pear
ln -s php-latest/bin/phpdbg phpdbg
ln -s php-latest/sbin/php-fpm php-fpmSTEP 8: link your local PHP to the php command. You will need to logout then log back in for php to switch to the local version instead of the installed version
# add this to .bashrc
if [ -d «$HOME/bin» ] ; then
PATH=»$HOME/bin:$PATH»
fiHow to Install PHP 8 on Ubuntu 20.04/18.04
This tutorial will take you step by step to install the latest PHP 8 version or upgrade to the latest on your Ubuntu 20.04 or 18.04 systems or also your Ubuntu server. Next, you’ll see how to configure it with Apache and Nginx.
PHP 8 is officially released on November 26th, 2020. It brings several new features and improvements that will make your life easier as a programmer
Prerequisites
Before you can continue with this tutorial, you’ll need to have the following prerequisites:
- A Ubuntu server with sudo privileges.
Updating your Ubuntu System Packages
First, you need to update your Ubuntu server with the latest packages by using the following command:
This will update the package index and update the installed packages to the latest version.
Adding a PPA for PHP 8
Next, you need to use a PPA for PHP 8. Head back to your terminal and add the ondrej/php which contains the latest PHP 8 package and compatible PHP extensions:
Now you are ready to install PHP 8.
Installing PHP 8 for Apache Server
Let’s now see how to install PHP 8
Execute the following command to install PHP 8
After the installation has completed, you can confirm the installation using the following command
Installing PHP 8 FPM for Nginx
For Nginx you need to install FPM, execute the following command to install PHP 8 FPM
After the installation has completed, confirm that PHP 8 FPM has installed correctly with this command
Install PHP 8 Extensions
Installing PHP extensions are simple with the following syntax.
Now, install some commonly used php-extensions with the following command.
Configure PHP 8 for Apache
Now we configure PHP for Web Applications by changing some values in php.ini file.
For PHP 8 with Apache the php.ini location will be in following directory.
Hit F6 for search inside the editor and update the following values for better performance.
Once you have modified your PHP settings you need to restart your Apache for the changes to take effect.
Configure PHP 8 for Nginx
For PHP 8 FPM with Nginx the php.ini location will be in following directory.
Hit F6 for search inside the editor and update the following values for better performance.
Once you have modified your PHP settings you need to restart PHP FPM for the changes to take effect.
Configure PHP 8 FPM Pools
PHP 8 FPM allows you to configure the user and group that the service will run under. You can modify these with these commands
Change the following lines by replacing the www-data with your username .
Hit CTRL+X and Y to save the configuration and check if the configuration is correct and restart PHP.
Restart PHP 8.0 FPM
Once you have updated your PHP FPM settings you need to restart it to apply the changes.
Now you are having PHP 8 Installed and configured.
Become a Linux System Administrator and maintain virtual servers in a multi-user environment.
Upgrade to PHP 8 for Apache
Once you have installed PHP 8 you need to upgrade to the latest installed version of PHP.
You need to disable the old PHP version and enable the new PHP version 8.
This command will disable the PHP 7.4 module.
This command will enable the PHP 8 module.
Now you need to restart Apache for the changes to take effect.
Upgrade to PHP 8 for Nginx
For Nginx you need to update the PHP-FPM socket in your Nginx configuration located inside the sites-available directory. This will be located inside the location block location
Programming — PHP
PHP is a general-purpose scripting language suited for Web development. PHP scripts can be embedded into HTML. This section explains how to install and configure PHP in an Ubuntu System with Apache2 and MySQL.
This section assumes you have installed and configured Apache2 Web Server and MySQL Database Server. You can refer to the Apache2 and MySQL sections in this document to install and configure Apache2 and MySQL respectively.
Installation
PHP is available in Ubuntu Linux. Unlike Python, which is installed in the base system, PHP must be added.
To install PHP and the Apache PHP module you can enter the following command at a terminal prompt:
You can run PHP scripts at a terminal prompt. To run PHP scripts at a terminal prompt you should install the php-cli package. To install php-cli you can enter the following command:
You can also execute PHP scripts without installing the Apache PHP module. To accomplish this, you should install the php-cgi package via this command:
To use MySQL with PHP you should install the php-mysql package, like so:
Similarly, to use PostgreSQL with PHP you should install the php-pgsql package:
Configuration
If you have installed the libapache2-mod-php or php-cgi packages, you can run PHP scripts from your web browser. If you have installed the php-cli package, you can run PHP scripts at a terminal prompt.
By default, when libapache2-mod-php is installed, the Apache 2 Web server is configured to run PHP scripts using this module. Please verify if the files /etc/apache2/mods-enabled/php8.*.conf and /etc/apache2/mods-enabled/php8.*.load exist. If they do not exist, you can enable the module using the a2enmod command.
Once you have installed the PHP related packages and enabled the Apache PHP module, you should restart the Apache2 Web server to run PHP scripts, by running the following command:
Testing
To verify your installation, you can run the following PHP phpinfo script:
You can save the content in a file phpinfo.php and place it under the DocumentRoot directory of the Apache2 Web server. Pointing your browser to http://hostname/phpinfo.php will display the values of various PHP configuration parameters.
References
For more in depth information see the php.net documentation.
There are a plethora of books on PHP 7 and 8. A good book from O’Reilly is Learning PHP, which includes an exploration of PHP 7’s enhancements to the language.