Php open basedir tmp

phpMyadmin can’t import file with error: open_basedir > enabled without access to the /tmp directory

After installing apache-mysql-php on Debian. I can’t import .sql files to MySQL through phpMyAdmin. Error says:

Uploaded file cannot be moved, because the server has open_basedir enabled without access to the /tmp directory (for temporary files).

open_basedir is commented in both /etc/php5/apache2/php.ini and /etc/php5/cli/php.ini and safe_mode is OFF. I set 777 permission to /var/tmp still get the error.

Have you restarted the webserver after making your changes? Also double check phpinfo(); to make sure you’re modifying the right php.ini.

4 Answers 4

While you say that open_basedir is commented out, what is the output of phpinfo() ? There should be an open_basedir setting in there. And perhaps there is an .htaccess file—or another php.ini config—that is setting open_basedir somewhere. That said, according to the official phpMyAdmin docs:

Since version 2.2.4, phpMyAdmin supports servers with open_basedir restrictions. However you need to create temporary directory and configure it as $cfg[‘TempDir’]. The uploaded files will be moved there, and after execution of your SQL commands, removed.

So while you say that open_basedir is commented out—implying it is not being used—perhaps you should open up your phpMyAdmin config and set the cfg_TempDir to point to /var/tmp . The config.php file is located here in Ubuntu 12.04:

/usr/share/phpmyadmin/config.inc.php 

Note that the error message refers to /tmp/ but you are referring to /var/tmp/ .

Читайте также:  Удаление значения массива python

Additionally, the issue seems to be covered here in the community wiki reference for PHP related error:

The fix is normally to change the PHP configuration, the related setting is called open_basedir.

Sometimes the wrong file or directory names are used, the fix is then to use the right ones.

So in your case you can perhaps adjust the php.ini to have this setting:

And note that the only php.ini that matters in a case of web related issues like this is /etc/php5/apache2/php.ini . The CLI php.ini located here /etc/php5/cli/php.ini is strictly for CLI use and has nothing to do with the Apache PHP module.

Источник

sys_get_temp_dir

Returns the path of the directory PHP stores temporary files in by default.

Parameters

This function has no parameters.

Return Values

Returns the path of the temporary directory.

Examples

Example #1 sys_get_temp_dir() example

// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam ( sys_get_temp_dir (), ‘Tux’ );

The above example will output something similar to:

See Also

User Contributed Notes 11 notes

If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return «/tmp», not the true, much longer, somewhat dynamic path.

As of PHP 5.5.0, you can set the sys_temp_dir INI setting so that this function will return a useful value when the default temporary directory is not an option.

This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.

It’s not documented but this function does not send the path with trailing spaces, actually it drops the slash if it exists.

it should be mentioned that the return value of sys_get_temp_dir() can be set using the ini-directive ‘sys_temp_dir’ globally as well as per directory by using
php_admin_value sys_temp_dir /path/to/tmp

A very helpful thing to note when on Linux:

If you are running PHP from the commandline you can use the environment variable: TMPDIR — to change the location without touching php.ini. — This should work on most versions of PHP.

Example file: test.php
echo sys_get_temp_dir () . PHP_EOL ;
?>

And then running:

TMPDIR=/custom/location php test.php
/custom/location

This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:


php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp

Within this config it still returns /tmp

That is important for the purposes of building paths through concatenation to know that sys_get_temp_dir does not include a path separator at the end.

So, sys_get_temp_dir() will return whatever your temp dir is set to, by default:

If you attempted to concatenate another dir name temp and use the following:

That would actually attempt to generate:
/tmpsome_dir

It would likely result in a permission error unless you are running a php script as a super user.

Instead you would want to do:
mkdir( sys_get_temp_dir() . DIRECTORY_SEPARATOR. ‘some_dir’ );

which would create:
/tmp/some_dir

I don’t know if Windows or other platforms include a directory separator at the end. So if you are writing something a bit more general you may want to check for the path separator at the end and if it is not there append it.

On windows, when PHP is used as CLI, this function will return the temp directory for the current user e.g. C:\Users\JohnSmith\AppData\Local\Temp\9 instead of C:\Windows\Temp.

Источник

Настройка open_basedir в php

error.jpg

При выборе аватара выскакивает ошибка. Форум после восстановления, но данный плагин переустанавливал и все равно ошибка.

baltun

open_basedir в php надо настраивать, нет доступа для записи во временную папку которая находится по пути: /home/admin/tmp
Такая ошибка может быть не только у этого приложения, а любого другого, которому требуется переменная open_basedir

TOP-ic

open_basedir в php надо настраивать, нет доступа для записи во временную папку которая находится по пути: /home/admin/tmp
Такая ошибка может быть не только у этого приложения, а любого другого, которому требуется переменная open_basedir

baltun

Функция PHP open_basedir — это мера безопасности, которая предотвращает открытие файлов и скриптов, которые находится вне «домашней» директории. Если настройка PHP open_basedir включена, то все файловые операции ограничиваются одной папкой на сервере, не допуская доступа к скриптам неавторизованных пользователей. Когда скрипт пытается открыть файл, который находится вне корневой директории, например fopen() или gzopen(), проверяется путь у файлу. Когда файл находится вне разрешенной директории, PHP откажет в его выполнении и появится ошибка, вида:

is not within the allowed path(s): (/home/user_name:/usr/lib/php:/usr/local/lib/php:/tmp)
  1. Решением может послужить отключение этой функции, либо разрешение доступа к файлам некоторым привилегированным учетным записям, либо же разрешить доступ PHP скриптам к некоторым папкам.
  • Если Вы используете cPanel WebHost Manager (WHM), Вы можете легко отключить опцию open_basedir, или исключить некоторых пользователей из списка, для разрешения им доступа. В секции “Security” откройте “Tweak Security”, затем нажмите “Configure” для “Php open_basedir Tweak”. Здесь Вы можете включить или отключить php фунцию open_basedir, добавить или убрать некоторые хосты.
  • Если Вы используете панель управления хостингом Plesk, Вам нужно будет вручную отредактировать файл конфигурации Apache — vhost.conf и vhost_ssl.conf, и добавить или изменить линии php_admin_value open_basedir на следующие:

php_admin_value open_basedir none php_admin_value open_basedir /full/path/to/dir:/full/path/to/directory/httpdocs:/tmp
Пути к папкам (вверху пример), которые находятся после open_basedir, это директории, к которым разрешен доступ для PHP скриптов на сервере. Вы можете добавить сюда больше файлов и папок, разделяя их двоеточием “:”. Будьте внимательны, чтобы не нарушить безопасность Вашей системы.​

После завершение, запустите команду ниже, чтобы изменения вступили в силу и перезапустите Apache httpd сервер (apache2ctl restart или httpd restart)​

2. Если нужно вручную отредактировать настройки Apache, чтобы выключить защиту PHP open_basedir, откройте файл httpd.conf, найдите линию, которая начинается так:​

php_admin_value open_basedir …..
Чтобы отключить функцию для определенной учетной записи на сервере, используйте следующую строчку:
php_admin_value open_basedir none

3. Вы всегда можете ограничить защиту для определенных папок, без его полного отключения функции open_basedir. Для этого просто внесите список разрешенных папок, разделяя их двоеточием. Например, для разрешения доступа к директории /new_directory код будет таким:​

php_admin_value open_basedir “/home/user_account/:/usr/lib/php:/usr/local/lib/php:/tmp” php_admin_value open_basedir “/home/user_account/:/usr/lib/php:/usr/local/lib/php:/tmp:/new_directory”
Перезапустите Apache сервер. Обратите внимание, что ограничение ввреху, это только префикс, а сама папка. Т.е. использование, к примеру, “open_basedir = /dir/incl” также откроет доступ к папкам “/dir/include” или “/dir/incls”, если таковые имеются. Для ограничения доступа только к одной специфической директории, используйте слеш в конце: “open_basedir = /dir/incl/”.

Источник

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.

Источник

Оцените статью