PHP open_basedir
We have two options
— global config, one config file in the include folder /usr/local/php/php.d/ and in PHP selector include folders
— per-user config, the securest option as it restricts the user to his /home/USERNAME folder and also disables users from using custom php.ini files.
Global Configuration
The securest method do this correctly and to prevent users from overriding this is to place the config into the include file. Please note that if you set this into /usr/local/php/php.ini then custom user php.ini will be able to disable it. Please note that global config allows full /home folder access while per user restricts users to /home/USERNAME folder which is much more secure.
One line command to create a file and config:
echo "open_basedir = /home:/tmp:/var/tmp:/usr/local/lib/php/" > /usr/local/php/php.d/open_basedir.ini
You can also do it by yourself by creating a file: /usr/local/php/php.d/open_basedir.ini with the following content:
open_basedir = /home:/tmp:/var/tmp:/usr/local/lib/php/
To enable it for other php versions from the PHP selector you can create this config files with the same content:
/opt/alt/php44/usr/php/php.d/open_basedir.ini /opt/alt/php52/usr/php/php.d/open_basedir.ini /opt/alt/php53/usr/php/php.d/open_basedir.ini /opt/alt/php54/usr/php/php.d/open_basedir.ini /opt/alt/php55/usr/php/php.d/open_basedir.ini /opt/alt/php56/usr/php/php.d/open_basedir.ini /opt/alt/php70/usr/php/php.d/open_basedir.ini /opt/alt/php71/usr/php/php.d/open_basedir.ini /opt/alt/php72/usr/php/php.d/open_basedir.ini /opt/alt/php7/usr/php/php.d/open_basedir.ini
Testing:
Create a phpinfo file on some account/domain/subdomain . and open it with a browser.
open_basedir value should show info from the config
PHP info file example phpinfo.php
Per User open_basedir
To enable per-user open_basedir you can create a php.ini file in the users /home folder.
Example: /home/USERNAME/php.ini ,make sure the file is owned by root so that the user can’t disable it.
echo "open_basedir = /home/USERNAME:/tmp:/var/tmp:/usr/local/lib/php/" > /home/USERNAME/php.ini chown root.root /home/USERNAME/php.ini chmod 555 /home/USERNAME/php.ini
** Don’t forget to replace the USERNAME.
Please note that this option will also disable all further custom users php.ini files per folder, for example: /home/USERNAME/public_html/php.ini will not be loaded.
You can also place it into public_html folder but then users will be able to run custom php.ini files per folder and they can disable open_basedir.
RECOMMENDATION
We recommend using the per-user configuration of open_basedir as it will provide much higher security and isolate each client.
NGINX + PHP-FPM
configuration files are:
/etc/nginx/conf.d/vhosts/DOMAIN.conf
/etc/nginx/conf.d/vhosts/DOMAIN.ssl.conf
under fastcgi_param add one more line and reload/restart nginx
fastcgi_param PHP_ADMIN_VALUE "open_basedir =/home/USERNAME:/tmp:";
** Note that manual editing of the webserver vhost files is not recommended as those files get rebuilt from the template on each change.
Try checking the instructions here for the custom template build.
APACHE + PHP-FPM
Configuration files are all user existing php-fpm configuration files, to get the list of files you can use this
ls -la /opt/alt/php-fpm*/usr/etc/php-fpm.d/users/USERNAME.conf
php_admin_value[open_basedir] = /home/USERNAME:/tmp
** Note that editing any of those files requires to restart php-fpm version you edited.
** Note that manual editing of the webserver vhost files is not recommended as those files get rebuilt from the template on each change.
Try checking the instructions here for the custom template build.
Для чего нужна и как использовать open_basedir
Директива open_basedir указывается в конфигурационном файле PHP (php.ini) и устанавливает директории, к которым может иметь доступ PHP. Под доступом понимаются любые действия с файлами: открытие (например, функции fopen() или gzopen()), записи и выполнения. Если директива open_basedir установлена и делается попытка запустить файл, который находится за пределами перечисленных директорий, то скрипт не запустится и выдаст ошибку:
[Wed Apr 1 13:11:34 2020] PHP Warning: Unknown: open_basedir restriction in effect. File(/usr/share/seeker/template/nearyou/php/info.php) is not within the allowed path(s): (/srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/) in Unknown on line 0
Пример значения open_basedir:
open_basedir = /srv/http/:/etc/webapps/:/usr/share/webapps/:/tmp/:/home/mial/
В указанном примере разрешён запуск скриптов PHP, а также операции с файлами в директориях:
Директива open_basedir оказывает влияние на многие функции. Больше всего в ней смысла при использовании на уровне конфигурационных файлов веб-сервера на уровне директорий или виртуальных хостов.
По умолчанию, если значение open_basedir не установлено, разрешены файловые операции в любых директориях компьютера (на которые достаточно прав).
Опция open_basedir может распространяться не только на функции для работы с файловой системой; например, если MySQL настроен использовать драйвер mysqlnd, то LOAD DATA INFILE подпадает под опцию open_basedir . Множество функций PHP также использует open_basedir.
Специальное значение . (точка) обозначает, что рабочая директория скрипта будет использована в качестве базовой директории. Однако, это немного опасно, так как текущая директория скрипта может быть легко изменена с помощью chdir().
В httpd.conf, open_basedir может быть выключена (например, для некоторых виртуальных хостов) тем же способом, что и любая другая конфигурационная директива:
php_admin_value open_basedir none
В Windows разделяйте директории символом ; (точкой с запятой). На всех остальных системах, разделяйте директории символом : (двоеточием). При работе в качестве модуля Apache, пути open_basedir автоматически наследуются от родительских директорий.
Связанные статьи:
How to:- set specific path/directory for “open_basedir” in PHP or Apache?
open_basedir function used to define the locations or paths from which PHP is allowed to access files using function like fopen() and gzopen(). If the file is outside of the location or paths defined by open_basedir, PHP will refuse to open and read it. You can also not use a symbolic link as a workaround because the path that the symbolic link resolves to falls under the restrictions of the open_basedir function.
The default open_basedir restrictions for shared Linux hosting accounts have no value. PHP scripts can access all directories within your hosting account.
You can turned off the open_basedir restrictions editing Apache configuration file httpd.conf using the following line : php_admin_value open_basedir none
Set open_basedir in Apache
You can set the open_basedir restriction in httpd.conf file like below.
php_admin_value open_basedir "/var/www/vhosts/httpdocs"
Set open_basedir globally
You can also set the open_basedir restriction globally editing php.ini file. Put the below line in php.ini fine.
open_basedir = /var/www/vhosts/httpdocs
Now restart the apache service to apply changes.
Set open_basedir in php.ini
To edit the open_basedir paths, open php.ini and add your directories using this format:
open_basedir = "/path/to/first/folder:/path/to/second/folder"
Verify open_basedir
You can create a phpinfo page under your document root path to verify the open_basedir set or not.
# cd /var/www/html/ # vim phpinfo.php
Save and closer file. Open your web browser and enter below URL and check the open_basedir value.
http://Domain_Name_or_IP_Address/phpinfo.php