当通过 nginx 访问时,Php 在 /tmp/systemd-private-nABCDE/tmp 中有自己的 /tmp

Php has its own /tmp in /tmp/systemd-private-nABCDE/tmp when accessed through nginx

我发现有关 php/tmp 文件夹的奇怪行为。 Php 在与 /tmp 一起使用时使用另一个文件夹。 Php 5.6.7,nginx,php-fpm。

我以两种方式执行相同的脚本:通过浏览器和通过 shell。但是当它通过浏览器启动时,文件不在真正的 /tmp 文件夹中:

<?php
$name = date("His");

echo "File /tmp/$name.txt\n";

shell_exec('echo "123" > /tmp/'.$name.'.txt');

var_dump(file_exists('/tmp/'.$name.'.txt'));

var_dump(shell_exec('cat /etc/*release | tail -n 1'));

php -f script.php

File /tmp/185617.txt
bool(true)
string(38) "CentOS Linux release 7.0.1406 (Core)

文件在哪里?在 /tmp

$ find / -name 185617.txt
/tmp/185617.txt

如果通过 http://myserver.ru/script.php 访问它,我得到

File /tmp/185212.txt
bool(true)
string(38) "CentOS Linux release 7.0.1406 (Core)

但是文件在哪里?

$ find / -name 185212.txt
/tmp/systemd-private-nABCDE/tmp/185212.txt

为什么 php 认为 /tmp 应该在 /tmp/systemd-private-nABCDE/tmp 中?

因为systemd is configured to give nginx a private /tmp。如果出于某种原因您必须 使用系统 /tmp,那么您将需要修改 .service 文件以读取 "PrivateTmp=no".

如果您在服务器上有 运行 个多个站点,那么我认为您需要保留 PrivateTmp=yes,这样每个站点即使在使用临时文件时也能保持隔离。否则可能是一个安全问题,我想。

Ignacio Vazquez-Abrams 的答案是正确的,但让我添加我的功能解决方案。

我尝试了 "multi-user.target.wants" 解决方案,它有效,但在重新启动后,但在某些时候,PrivateTmp 返回 true。 就像我对 Apache2 的主要用途是 PHP,我最终编辑了 php.ini 并取消了 sys_temp_dir.

行的注释

默认情况下,系统使用函数 sys_get_temp_dir 分配的临时目录。函数 sys_get_temp_dir 将 return "/tmp" 但事实是您的 tmp 文件存储在某些路径,例如 /tmp/systemd-private-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-apache2.service-YYYYYY//tmp/*。所以,对我来说工作是:

编辑 php.ini(路径可以在 PHP 个版本之间更改)

sudo nano /etc/php/7.2/cli/php.ini

然后取消注释 sys_temp_dir 行

; Directory where the temporary files should be placed.
; Defaults to the system default (see sys_get_temp_dir)
sys_temp_dir = "/tmp"