Php ini freebsd где
Перейти к содержимому

Php ini freebsd где

  • автор:

Установка Lighttpd, MySQL и PHP в FreeBSD 11.0

Lighttpd – это легкий открытый веб-сервер, оптимизированный для высокоскоростных сред, который при этом имеет низкий уровень использования ресурсов. Это отличная альтернатива широко используемым веб-серверам Nginx и Apache. В этом мануале вы узнаете, как установить и настроить Lighttpd на сервере FreeBSD 11.0, а также установить MySQL и PHP на веб-сервер Lighttpd, чтобы обслуживать веб-приложения и статический контент.

Требования

  • Сервер FreeBSD 11.0.
  • Пользователь с доступом к sudo (дополнительную информацию можно найти в руководстве Начало работы с FreeBSD).

1: Установка Lighttpd

Существует несколько методов установки Lighttpd, но в этом мануале веб-сервер будет установлен из пакетов. Установленные таким образом программы легче обновлять. Кроме того, это быстрее, чем компиляция из исходного кода или установка из портов.

Чтобы установить пакет Lighttpd, нужно обновить репозиторий системы:

sudo pkg update

Затем нужно загрузить и установить пакет lighttpd:

sudo pkg install lighttpd

Чтобы подтвердить, нажмите y.

При запуске сервера с конфигурацией по умолчанию вы увидите эту ошибку:

(network.c.260) warning: please use server.use-ipv6 only for hostnames, not without server.bind / empty address; your config will break if the kernel default for IPV6_V6ONLY changes

Это связано с тем, что конфигурация Lighttpd по умолчанию не полностью готова к поддержке IPv6. Чтобы избежать дальнейших ошибок, отредактируйте конфигурационный файл Lighttpd и отключите поддержку IPv6, для выполнения этого мануала она не нужна. Вы можете включить ее в будущем.

sudo ee /usr/local/etc/lighttpd/lighttpd.conf

Найдите этот раздел:

Замените enable на disable:

Найдите эту строку в конце файла:

Закомментируйте ее, она не нужна, если вы не используете IPv6.

Сохраните и закройте файл.

2: Установка и настройка MySQL

MySQL – это популярная система управления базами данных. Ее можно использовать для управления данными PHP-приложений, которые будет обслуживать веб-сервер Lighttpd.

MySQL, как и Lighttpd, можно установить из пакетов. Затем нужно настроить пароль для root-пользователя MySQL и отключить тестовые опции СУБД.

Поскольку ранее вы уже обновили репозиторий pkg, сейчас этого делать не нужно. Установите пакет MySQL:

sudo pkg install mysql57-server

Чтобы подтвердить установку, нажмите y.

После завершения установки добавьте MySQL в автозагрузку.

sudo sysrc mysql_enable=yes

Запустите сервис mysql-server:

sudo service mysql-server start

После запуска службы защитите установку MySQL с помощью сценария mysql_secure_installation. Он удалит некоторые опасные значения по умолчанию и заблокирует доступ к СУБД. Запустите интерактивный сценарий:

На экране появится сообщение:

Securing the MySQL server deployment.
Connecting to MySQL server using password in ‘/root/.mysql_secret’

Сценарий предложит настроить плагин для валидации паролей:

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Важно! Если эта функция включена, пароли, которые не соответствуют указанным критериям, будут отклонены, а MySQL выдаст ошибку. Это вызовет проблемы при использовании слабых паролей и программного обеспечения, которое автоматически настраивает учетные данные пользователя MySQL. Вы можете отключить валидацию паролей, но при этом вы должны использовать сложные уникальные пароли.

Чтобы включить функцию, нажмите Y. Чтобы продолжить, не включая эту функцию, нажмите любую клавишу.

Если вы решили включить эту функцию, вам будет предложено выбрать уровень валидации паролей. Самый сложный уровень – 2. Он отклоняет любые пароли, которые состоят из обычных слов и/или не содержат цифр, букв верхнего и нижнего регистра, а также специальных символов.

There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

Затем сценарий предложит изменить пароль пользователя root:

Change the password for root ? ((Press y|Y for Yes, any other key for No) :

Чтобы изменить его, введите Y.

Если вы включили валидацию пароля, сценарий проверит надежность текущего пароля root и предложит изменить этот пароль.

New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :

Введите новый пароль и нажмите Y.

Чтобы ответить на остальные вопросы, можно нажать Y и Enter. Это удалит некоторых анонимных пользователей и тестовую базу данных, отключит удаленный root доступ и обновит правила MySQL, чтобы изменения сразу вступили в силу.

На всякий случай можно перезапустить mysql-server:

sudo service mysql-server restart

3: Установка и настройка PHP

PHP будет обрабатывать код и отображать динамический контент. PHP может запускать сценарии, подключаться к MySQL, извлекать данные из БД и передавать обработанный контент веб-серверу для отображения.

PHP также можно установить из пакетов. Также вам понадобится пакет mysqli, который включает поддержку MySQL.

sudo pkg install php71 php71-mysqli

Lighttpd не предоставляет встроенную PHP-обработку, как некоторые другие веб-серверы, поэтому нужно использовать PHP-FPM (FastCGI Process Manager). Настройте Lighttpd для обработки запросов PHP с помощью этого модуля. Но прежде нужно настроить PHP-FPM. Откройте конфигурационный файл PHP-FPM:

sudo ee /usr/local/etc/php-fpm.d/www.conf

Настройте PHP-FPM для использования сокета Unix вместо сетевого порта. Это более безопасный вариант для сервисов, обменивающихся данными на одном сервере.

Найдите эту строку в файле:

Отредактируйте ее так:

Теперь нужно установить права собственности и доступа на сокет. Найдите такие строки:

.
;listen.owner = www
;listen.group = www
;listen.mode = 0660
.

Раскомментируйте раздел, удалив точки с запятой в начале каждой строки:

.
listen.owner = www
listen.group = www
listen.mode = 0660
.

Сохраните и закройте файл.

Затем создайте файл php.ini, который будет отвечать за общее поведение PHP. Есть два образца конфигурационного файла: php.ini-production и php.ini-development. В данной ситуации больше подходит php.ini-production, поэтому скопируйте его в /usr/local/etc/php.ini, где PHP будет искать свои настройки:

sudo cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini

Откройте php.ini в текстовом редакторе:

sudo ee /usr/local/etc/php.ini

В файле найдите раздел для cgi.fix_pathinfo. Он будет закомментирован; значение по умолчанию – 1:

Раскомментируйте эту строку и установите значение 0. Теперь PHP не будет пытаться выполнить части пути, если заданный файл не найден. Злоумышленники могут использовать эту функцию для выполнения вредоносного кода.

Сохраните и закройте файл.

Добавьте сервис php-fpm в автозагрузку:

sudo sysrc php_fpm_enable=yes

sudo service php-fpm start

4: Настройка Lighttpd для обслуживания приложений PHP

На этом этапе нужно настроить Lighttpd для поддержки FastCGI и PHP-FPM.

Сначала включите модуль FastCGI. Откройте конфигурационный файл Lighttpd:

sudo ee /usr/local/etc/lighttpd/modules.conf

Найдите такой раздел:

.
##
## FastCGI (mod_fastcgi)
##
#include «conf.d/fastcgi.conf»
.

Раскомментируйте строку include, удалив символ #. Если этой строки нет в файле, добавьте ее в конец файла:

.
##
## FastCGI (mod_fastcgi)
##
include «conf.d/fastcgi.conf»
.

Сохраните и закройте файл.

Отредактируйте конфигурационный файл FastCGI:

sudo ee /usr/local/etc/lighttpd/conf.d/fastcgi.conf

Этот файл содержит несколько закомментированных примеров. Добавьте следующие конфигурации в конец файла, чтобы настроить Lighttpd для обработки файлов PHP с помощью FastCGI и PHP-FPM:

.
fastcgi.server += ( «.php» =>
((
«socket» => «/var/run/php-fpm.sock»,
«broken-scriptfilename» => «enable»
))
)
.

Добавьте Lighttpd в автозагрузку.

sudo sysrc lighttpd_enable=yes

Запустите сервис lighttpd.

sudo service lighttpd start

5: Тестирование настройки

Чтобы убедиться, что Lighttpd может обслуживать страницы, создайте каталог /usr/local/www/data, в котором Lighttpd ищет данные, которые нужно обслужить.

sudo mkdir -p /usr/local/www/data

В этом каталоге создайте файл info.php. Этот файл поможет проверить, работает ли PHP, и позволит вам просматривать информацию о настройке веб-сервера в браузере:

sudo ee /usr/local/www/data/info.php

Добавьте в файл:

Сохраните и закройте файл.

Откройте в браузере ссылку:

На экране появится информация о настройке веб-сервера.

На этой странице отображается информация о текущей операционной системе, веб-сервере и том, как он обрабатывает файлы PHP. Если страница открылась, значит, веб-сервер может корректно обслуживать файлы PHP.

Если вместо страницы на экране появилось сообщение об ошибке 503 Service Not Available, убедитесь, что сервис php-fpm запущен правильно.

После проверки важно сразу же удалить файл info.php, поскольку он предоставляет конфиденциальную информацию о сервере любому пользователю, который ее запрашивает.

sudo rm /usr/local/www/data/info.php

Веб-сервер полностью готов к работе. Теперь вы можете размещать на нем веб-страницы, документы и другие файлы.

No php.ini!

I’ve just discovered I have no php.ini file on my server. According to phpinfo() it should be at /usr/local/etc/php.ini but I have no such file. According to the PHP manual I should copy either the development or production version to that location and then edit it for my needs, but I can’t find those on my machine either! I installed www/mod_php72 using ports-mgmt/pkg.

Where can I get these files for use on FreeBSD or do we really not need them?

Phishfry
  • Feb 17, 2020
  • #2
kjpetrie
  • Feb 17, 2020
  • Thread Starter
  • #3
m0nkey_
  • Feb 18, 2020
  • #4
usdmatt
  • Feb 18, 2020
  • #5

They are definitely provided with phpXX as I’ve installed this several times recently.

mod_php doesn’t actually seem to rely on any php package (don’t quite see what use it is as AFAIK mod_php can’t pass requests to an external service like php-fpm can), so have you actually got php installed?

Edit: Looking at the first post, if you’re running phpinfo on this host then you clearly have php installed. Which only leaves these files being removed somehow.

kjpetrie
  • Feb 18, 2020
  • Thread Starter
  • #6
SirDice
Administrator
  • Feb 18, 2020
  • #7

A number of php72-* modules are going to depend on lang/php72.

kjpetrie
  • Feb 18, 2020
  • Thread Starter
  • #8

Yes, but as you can see www/mod_php72 isn’t one of them, so it’s a little odd to expect someone to install it just to get a configuration file for something that doesn’t need it.

Actually, I do have lang/php72 installed in another jail, and I have now found the files I wanted there, but unless PHP is a jailbreak mechanism that shouldn’t be relevant.

msplsh
  • Feb 18, 2020
  • #9

If you don’t have the php.ini file, all that happens is that everything goes to defaults. It’s not the end of the world, everything runs as normal and the port doesn’t install it, only the template that you finally found. phpinfo() just lists whatever location it thinks you should put it.

If you’re complaining that mod_php doesn’t install a sample but php does. I guess technically you can just install mod_php since both of them seem to install libphp7.so, but you probably want some modules. Maintainers expect you to know what you’re doing in this case ��‍♂️

SirDice
Administrator
  • Feb 18, 2020
  • #10

Different locations, so there’s no conflict. They can’t both install /usr/local/etc/php.ini-development and /usr/local/etc/php.ini-production because that would cause a file conflict. As www/mod_php72 works just fine without a php.ini (it uses fairly sensible defaults) it’s left up to the system administrator to configure it (as a lot of ports do).

usdmatt
  • Feb 18, 2020
  • #11

I wasn’t aware of this but it seems mod_php actually creates a completely standalone binary of php that is loaded into Apache as a module. As such, it doesn’t actually require the php port/pkg installed.

This is a fairly unlikely situation to be in though as, as SirDice says, as soon as you want to install a module, lang/phpXX will be a dependency. Due to the way the ports tend to disable all php modules by default, it’s almost useless for any half serious application without at least one module.

Seeing as mod_php doesn’t seem to rely on lang/php, maybe there is a plausible argument that it should install the sample ini files, although they would likely need different names to the ones installed by lang/php. Personally I would just install lang/php anyway, as it seems odd to just have mod_php installed on its own, and as mentioned any modules will require it anyway.

kjpetrie
  • Feb 18, 2020
  • Thread Starter
  • #12

I’m not sure what the assumptions behind this are. All I know is I want to run PHP on my websites and I use PHP extensively to build site functionality. I don’t need any add-ons, just the core language to code in and write my back-end functions. I was just shocked to discover by accident that the php.ini file wasn’t where I expected it when I wanted to set error_reporting and display_errors globally rather than on a per-application basis and then, on further investigation, find even the sample files I’m supposed to adapt weren’t there to be copied. Yes, they’d have to have different names or be in a different directory to avoid clashes, but that’s trivial enough to sort out. One could even have the actual .ini in a different location to allow the CLI and web versions to be installed on the same machine with different configurations for different uses.

But it’s all getting a bit academic now as I’ve solved the initial problem and got sensible settings in place for development and production. I know the module runs well without the file — I’ve used it for months without the file and my sites work well and I doubt a third party accessing would notice any difference, but it’s one less thing to worry about now when I’m writing scripts, as my systems now have error handling defaults which suit their purposes. It’s also enabled me to disable phpinfo on the production server, as that’s obviously not something you’d want someone to see if they managed to trick the server into running it!

I don’t think this could be considered solved. I’m not sure it’s even soluble as there appears to be room for different opinions and we clearly don’t see the issue the same way. However, I no longer need help on this issue so I’m happy to leave it here.

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7a2928a04dff77a9 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

PHP 7.4 install, upgrade and harden

PHP logo. PHP is a scripting language that can be installed on FreeBSD and is especially suited to generate dynamic web content, for example in combination with Apache.
If you haven’t installed a webserver yet, read this article about: Installing Apache 2.4, upgrading and hardening. You may read this page with different needs.

Cutting edge technology

Cutting edge, or bleeding edge, technology refers to the most current and high-level IT developments. It is a category of technologies so new that they could have a high risk of being unreliable and lead adopters to incur greater expense in order to make use of them.
Indeed, when Nextcloud 11 came out it didn’t support PHP 7.2 right away. PHP 7.2 was too state-of-the-art to be compatible.

But a more profound issue took almost 2 years to solve: MySQL 8.0 using a new, more secure, default password hashing mechanism: caching_sha2_password. The Internet is littered with administrators having issues (» authentication method unknown to the client [caching_sha2_password]») and switched back to the legacy password hashing mechanism mysql_native_password. All technologies built upon PHP 7.3 and earlier encountered the problem. The issue was only fixed in PHP 7.4.

What this shows, besides a baffeling lack of communication, is that doing your reserach on whether you should upgrade when you could upgrade may save you a lot of time. Because worst case you need to deinstall the newest PHP, downgrade PHP, then downgrade the software package that is having issues and with incompatible database layouts, you may even need to restore an earlier backup of you database to get the software package working again. Ouch. Do your homework and save yourself time and hassle.

QJail portsnap configuration

When installing a PHP module in a jailed environment, you may encounter an error: The reason may be that QJail refuses to extract certain ports when executing a jail port update via qjail update -p .
In order to resolve the issue you can have a look at /usr/local/etc/qjail.portsnap.conf , which is used by /usr/local/bin/qjail . /usr/local/etc/qjail.portsnap.conf uses REFUSED lines to prevent a certain port directoy from extracting during an update.

To solve, take a look at the error message «/sharedfs/usr/ports/x11/libXpm». It shows an issue with «ports/x11» not being available. Allowing other ports as well may be needed for a smooth installation; trial & error.
An example of changing the default: Into, for example:

Install PHP 7.4

First check if PHP is already installed: If you’re already running PHP, consider upgrading (7.x to 7.y) or updating (7.3.x to 7.3.y). You can skip to the upgrade chapter: Upgrade PHP 7.x.x or Update PHP 7.4.x chapter.

Now install PHP 7.4, PHP modules and Apache module: php74-extensions installs: You can decide what modules you need and install them with pkg install or the commandline GUI. When using phpMyAdmin, Nextcloud and some graphical tools, the modules below come in handy.
Using pkg install: Instead of using pkg install you may also build from FreeBSD ports. In this case you can use a commandline GUI to select the desired modules:

Configuration of PHP 7.4 and Apache 2.4

Hardening PHP 7.4

Testing PHP 7.4

Upgrade PHP 7.x.x

With upgrading is meant to upgrade from a minor to another minor version, like: PHP 7.3.x to PHP 7.4.x. But also from one major version to another, like PHP 7.4.x. to PHP 8.0.x.

First check what version you’re running: If you’re already using the «latest version», PHP 7.4 as of this writing, then you can skip to the update chapter: Update PHP 7.4.x. You can check here if you’re running the latest version; ‘latest preview version’ is experimental, do not use it.

If you’re running an older version, first check what modules you have installed. Because we want to install newer onces, after removing the old modules; copy paste the output for later reading: Now delete the old versions and install the new versions: php74-extensions installs: You can decide what modules you need and install them with pkg install or the commandline GUI. When using phpMyAdmin, Nextcloud and some graphical tools, the modules below come in handy.
Using pkg install: Instead of using pkg install you may also build from FreeBSD ports. In this case you can use a commandline GUI to select the desired modules:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *