PHP

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page PHP and the translation is 55% complete.
Outdated translations are marked like this.
Other languages:
Resources

PHP — это скриптовый язык общего назначения, предназначенный для создания на стороне сервера динамических веб-страниц.

Установка

USE-флаги

Наиболее важные USE-флаги пакета PHP, USE-флаги SAPI (Server API), это apache2, cgi и fpm. Помимо этих USE-флагов, существует множество других USE-флагов, предназначенных для включения различных возможностей интерпретатора PHP:

USE flags for dev-lang/php The PHP language runtime engine

acl Add support for Access Control Lists
apache2 Add Apache2 support
apparmor Support FPM application confinement through sys-libs/libapparmor
argon2 Enable password hashing algorithm from app-crypt/argon2
avif Add AV1 Image Format (AVIF) support
bcmath Enable the BCMath Arbitrary Precision Mathematics extension
berkdb Add support for sys-libs/db (Berkeley DB for MySQL)
bzip2 Enable bzip2 compression support
calendar Add support for calendars (not using mcal!)
capstone Support opcache JIT disassembly through dev-libs/capstone
cdb Add support for the CDB database engine from the author of qmail
cgi Add CGI script support
cjk Add support for Multi-byte character languages (Chinese, Japanese, Korean)
cli Enable the Command-Line Interface (CLI) SAPI
coverage Include gcov symbols for test coverage and lcov reports. Only useful for extension developers, and requires GCC.
ctype Enable the Character type checking (ctype) extension
curl Add support for client-side URL transfer library
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
embed Enable embed SAPI
enchant Enable the Enchant spelling library extension using app-text/enchant
exif Add support for reading EXIF headers from JPEG and TIFF images
ffi Enable the Foreign Function Interface (FFI) extension using dev-libs/libffi
fileinfo Enable the File Information extension
filter Enable the Data Filtering extension
firebird Add support for the Firebird relational database
flatfile Add dbm support for flat files
fpm Enable the FastCGI Process Manager SAPI
ftp Add FTP (File Transfer Protocol) support
gd Enable the Image Processing and GD extension (requires media-libs/libjpeg-turbo and media-libs/libpng)
gdbm Add support for sys-libs/gdbm (GNU database libraries)
gmp Add support for dev-libs/gmp (GNU MP library)
iconv Enable support for the iconv character set conversion library
imap Add support for IMAP (Internet Mail Application Protocol)
inifile Add dbm support for .ini files
intl Enables the intl extension for extended internalization support
iodbc Add support for iODBC library
ipv6 Support IPv6 connectivity in fopen and friends, and v6 address conversions in functions like inet_pton and inet_ntop.
jit Enable PCRE JIT support
kerberos Add kerberos support
ldap Add LDAP support (Lightweight Directory Access Protocol)
ldap-sasl Add SASL support for the PHP LDAP extension using dev-libs/cyrus-sasl
libedit Use the libedit library (replacement for readline)
lmdb Enable support for dev-db/lmdb db backend
mhash Add support for the mhash library
mssql Add support for Microsoft SQL Server database
mysql Add mySQL Database support
mysqli Add support for the improved mySQL libraries
nls Add Native Language Support (using gettext - GNU locale utilities)
oci8-instant-client Use dev-db/oracle-instantclient-basic as Oracle provider instead of requiring a full Oracle server install
odbc Add ODBC Support (Open DataBase Connectivity)
opcache Enables built-in opcode cache, replacing pecl-apc et al.
pcntl Enable the Process Control extension
pdo Enable the PHP Data Objects extension
phar Enables the phar extension to provide phar archive support
phpdbg Enable the PHP Debug Command Line SAPI (like gdb for php)
posix Add support for POSIX-compatible functions
postgres Add support for the postgresql database
qdbm Add support for the qdbm (Quick Database Manager) library
readline Enable support for libreadline, a GNU line-editing library that almost everyone wants
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
session Add persistent session support
session-mm Include dev-libs/mm support for session storage
sharedmem Enable the shmop extension
simplexml Enable the SimpleXML extension
snmp Add support for the Simple Network Management Protocol if available
soap Add support for SOAP (Simple Object Access Protocol)
sockets Add support for tcp/ip sockets
sodium Enable support for crypto through dev-libs/libsodium
spell Add dictionary support
sqlite Add support for sqlite - embedded sql database
ssl Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security)
systemd Enable use of systemd-specific libraries and features like socket activation or session tracking
sysvipc Enable the PHP System-V semaphore, shared memory and IPC extension
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
threads Add threads support for various packages. Usually pthreads
tidy Add support for HTML Tidy
tokenizer Add support for the PHP file parser
tokyocabinet Enable support for dev-db/tokyocabinet db backend
truetype Add support for FreeType and/or FreeType2 fonts
unicode Add support for Unicode
valgrind Enable annotations for accuracy. May slow down runtime slightly. Safe to use even if not currently using dev-debug/valgrind
webp Add support for the WebP image format
xml Add support for XML files
xmlreader Enable the XMLReader extension
xmlwriter Enable the XMLWriter extension
xpm Add support for XPM graphics format
xslt Build the XSL extension
zip Enable support for ZIP archives
zlib Add support for zlib compression

По умолчанию ebuild устанавливает development версию php.ini. Для того, чтобы установить production версию, у которой более строгие настройки безопасности, но с помощью которой может быть сложнее отлаживать приложения, добавьте следующее в файл make.conf:

Расширения

Чтобы установить расширения, прежде всего определите, для каких версий PHP их следует скомпилировать. Это реализуется посредством установки переменной PHP_TARGETS:

ФАЙЛ /etc/portage/make.conf
PHP_TARGETS="php5-6"

Можно указать более одной версии; просто добавьте дополнительные версии, разделенные пробелами. Обратите внимание, что слот php называется "5.6", а соответствующее значение PHP_TARGETSphp5-6. Причина этого — в текущих ограничениях имен USE.

Emerge

После настройки USE-флагов, как показано выше, необходимо обновить систему, чтобы изменения вступили в силу:

root #emerge --ask --update --changed-use --deep @world

Запуск нескольких версий PHP

Одно из больших преимуществ использования Gentoo для разработки PHP — слотирование версий. Переключаться между несколькими версиями PHP очень просто, также как одновременно запускать несколько версий. Все это осуществляется с помощью команды eselect, предоставляемой пакетом app-eselect/eselect-php, который должен автоматически устанавливаться при установке PHP. Например, выбор нескольких версий PHP позволяет системе использовать PHP 7.0 для cli SAPI и PHP 5.6 для веб-сервера. Это также позволяет быстро протестировать приложение на разных версиях PHP.

For example, selecting different versions of PHP can allow a system to run PHP 7.0 for the cli SAPI but PHP 5.6 for the system's web server. It also allows system administrators or application developers to quickly test an application on different versions of PHP.

Чтобы вывести доступные версии для cli SAPI, используйте команду:

root #eselect php list cli
 [1]   php5.5 
 [2]   php5.6 *   
 [3]   php7.0

Версия, отмеченная символом *, является текущей активной версией. Чтобы посмотреть другие SAPI, замените cli на fpm, cgi или apache2.

Чтобы переключить версию:

root #eselect php set cli 3

Номер 3 в этом примере соответствует номеру из вывода суб-команды list, приведенной выше. PHP версии 7.0 теперь используется для командной строки:

root #php -v
PHP 7.0.10-pl0-gentoo (cli) (built: Aug 23 2016 12:38:44) ( NTS )

Конфигурация

Конфигурация PHP находится в каталоге /etc/php, который содержит один подкаталог для каждого SAPI и для каждой версии PHP. Например, конфигурационные файлы для PHP-5.6 apache2 SAPI устанавливаются в /etc/php/apache2-php5.6.

Веб-серверы

Чтобы использовать PHP на стороне сервера, веб-сервер должен быть установлен и настроен для использования PHP. Далее кратко рассматривается несколько популярных веб-серверов.

Nginx

Просто скомпилируйте nginx, чтобы установить его:

root #emerge --ask www-servers/nginx
Важно
Если пользовательские установки NGINX_MODULES_HTTP установлены в make.conf, убедитесь, что модуль fastcgi включен.

После установки Nginx измените раздел server в /etc/nginx/nginx.conf примерно таким образом:

ФАЙЛ /etc/nginx/nginx.confЧасть конфигурации nginx, в которой настраивается работа PHP через FastCGI
server {
                listen 127.0.0.1;
                server_name localhost;
 
                access_log /var/log/nginx/localhost.access_log main;
                error_log /var/log/nginx/localhost.error_log info;
 
                root /var/www/localhost/htdocs;
 
                location ~ .php$ {
                        fastcgi_pass 127.0.0.1:9000;
                        include fastcgi.conf;
                }
        }

Теперь запустите соответствующие сервисы, чтобы получить рабочий сайт. Init-скрипт php-fpm запускает PHP FastCGI Process Manager. FastCGI позволяет веб-серверам передавать вычисления PHP этому менеджеру процессов.

When running OpenRC as the service manager:

root #service nginx start
root #service php-fpm start

For systemd:

root #systemctl start nginx
root #systemctl start php-fpm@7.2
Заметка
The version number after the php-fpm service name will change based on the available version of PHP. Adjust as appropriate.

lighttpd

Предупреждение
Не включайте USE-флаг php для www-servers/lighttpd. Это может сломать сборку.

Убедитесь в том, что lighttpd собран с поддержкой fastcgi и USE-флаг php выключен:

ФАЙЛ /etc/portage/package.use
www-servers/lighttpd fastcgi -php

Lighttpd устанавливает конфигурационный файл FastCGI по умолчанию, но, к сожалению, он работает только со старым PHP FCGI SAPI, а не с общей установкой FCGI. Поскольку USE-флаг php был выключен, этот файл не будет установлен. Тем не менее, он является хорошей основой для конфигурационного файла, который можно использовать с FPM.

Отредактируйте /etc/lighttpd/mod_fastcgi.conf:

ФАЙЛ /etc/lighttpd/mod_fastcgi.confВключение FastCGI в lighttpd
server.modules += ("mod_fastcgi")
fastcgi.server = ( ".php" =>
  ( "localhost" =>
    (
      "host" => "127.0.0.1",
      "port" => "9000"
    )
  )
)

Обратите внимание на строки host и port.

Поскольку в Gentoo входит рабочий файл php-fpm.ini, который находятся в /etc/php/fpm-php5/php-fpm.ini, и init-скрипт, это все, что требуется, чтобы запустить сервисы:

root #/etc/init.d/php-fpm start
root #/etc/init.d/lighttpd start

Apache (mod_php)

Чтобы Apache загружал модуль PHP5 (mod_php), добавьте -D PHP в переменную APACHE2_OPTS в /etc/conf.d/apache2. Возможно, пользователи помнят, что раньше было необходимо также добавлять версию PHP (например, -D PHP5). Однако начиная с app-eselect/eselect-php версии 0.8.1 переменная была изменена на -D PHP, чтобы упростить интеграцию будущих крупных версий.

ФАЙЛ /etc/conf.d/apache2Настройка Apache для загрузки mod_php
## (settings for PHP5 and above)
APACHE2_OPTS="-D PHP"

Убедитесь в том, что PHP собран с USE-флагом apache2.

Если по какой-либо причине в системе отсутствует файл интеграции модуля PHP /etc/apache2/modules.d/70_mod_php.conf, в настоящее время предоставляемый пакетом app-eselect/eselect-php, если он установлен с USE-флагом apache2, добавьте его вручную. Ниже показано его текущее содержимое.

ФАЙЛ /etc/apache2/modules.d/70_mod_php.conf
<IfDefine PHP>
	# The mod_php.so symlink is controlled by
	# eselect-php. However, the module name changed from
	# php5_module to php7_module so we can't blindly load whatever
	# is there. Instead we let eselect-php manage a small
	# configuration file that loads the appropriate module.
	#
	# This is relative to ServerRoot (see httpd.conf).
	Include ../../../var/lib/eselect-php/mod_php.conf
 
	# Tell apache that mod_php should handle PHP files.
	#
	# NOTE: Avoiding AddHandler/AddType for security (bug
	# #538822). Please read the related news item!
	<FilesMatch "\.(php|php[57]|phtml)$">
		SetHandler application/x-httpd-php
	</FilesMatch>
 
	# PHP source files which are meant to be displayed as
	# syntax-highlighted source code.
	<FilesMatch "\.phps$">
		SetHandler application/x-httpd-php-source
	</FilesMatch>
 
	DirectoryIndex index.php index.phtml
</IfDefine>

Хотя в системе может быть установлено несколько версий PHP, Apache может использовать только одну версию PHP. Команда eselect php используется для переключения активных версий PHP.

To change the version of PHP handled by Apache, first list the available versions for the apache2 Server Application Programming Interface (SAPI):

root #eselect php list apache2
 [1]   php5.3
 [2]   php5.4 *
 [3]   php5.5

Change it to the version of choice:

root #eselect php set apache2 N

Substitute N in the example above to the requested number in the output of eselect php list apache2 as displayed earlier on.

To verify the PHP module works, create a test page:

ФАЙЛ /var/www/localhost/htdocs/index.phpPHP test page
<html>
 <body>
  <?php phpinfo(); ?>
 </body>
</html>

Now, suppress or rename /var/www/localhost/htdocs/index.html and open the test page: http://localhost/

A table describing the PHP settings should be visible.

Apache (fcgid)

See enabling PHP through fcgid in the Apache article.

Apache (mod_proxy_fcgi)

See enabling PHP-FPM through mod_proxy_fcgi in Apache 2.4.

Смотрите также

External resources