为什么不能将信息写入 /tmp 目录而不是 /var/www/html?

Why can't write info into /tmp directory instead of /var/www/html?

LAMP 安装在我的本地电脑上,据我所知,字符串 xxxx 可以用下面的 PHP 函数写入 /tmp/test

file_put_contents("/tmp/test","test1 test2") 

cat ajax_get.php

<?php
    $str = "test1 test2";
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
    $str = implode(" ",$_GET);
    file_put_contents("/tmp/test",$str);
    print($str);
?>

为什么ajax_get.php中的命令file_put_contents("/tmp/test",$str);不起作用?

file_put_contents换成

也没用
$handle=fopen("/tmp/test","w");
fwrite($handle,$str);
fclose($handle);

可能是目录权限的问题,如果我在ajax_get.php

中更改以下语句
    file_put_contents("/tmp/test",$str);

进入

    file_put_contents("test",$str);

和运行前面的过程,ajax_get.php/var/www/html/test

中创建一个文件
cat /var/www/html/test
test1 test2

显示 /tmp 目录的权限。

ls -al /tmp
total 76
drwxrwxrwt 16 root    root    12288 Dec 10 18:39 .
drwxr-xr-x 23 root    root     4096 Dec  1 08:03 ..

.为当前目录/tmp,其权限为777(rwxrwxrwx), 为什么 PHP 无法将文件写入 /tmp 目录?

file_get_contents 方法的 return 值在 php manuel 页面上解释为 此函数 returns 数字写入文件的字节数,失败时为 FALSE。 所以 file_get_contents 它必须是 return。首先,你必须检查这个 returns.

其次,您想要创建一个文件到一个看起来只有 root 用户权限的文件夹。 Apache用户没有root权限,所以不能写。请检查此 url 权限,我建议您在更改文件夹权限时要小心。

您没有与我们分享 file_put_contents("/tmp/test",$str); 的 return,但我假设您实际上正在编写适当的字节。

在这种情况下,考虑到权限看起来没问题,而且您没有说收到错误消息,最有可能的情况是 systemd 配置有问题。

您的 Apache/PHP 进程正在正确写入该位置,但是 systemd has a configuration setting that allows for each process to have its own /tmp directory.

PrivateTmp=
    Takes a boolean argument. If true sets up a new file system
     namespace for the executed processes and mounts a 
     private /tmp directory inside it, that is not shared by     
     processes outside of the namespace. This is useful to secure 
     access to temporary files of the process, but makes sharing
     between processes via /tmp impossible. 

Defaults to false.

在这种情况下,您作为普通用户或 root 用户看到的 tmp 与 apache/php 看到的 tmp 目录不同。例如,阅读更多关于此 here 的信息。

您可以禁用 Apache 的 PrivateTmp 设置,但我认为选择不同的路径来存储文件并授予 apache/PHP 进程写入权限会更容易。

尽管有目录权限,但仍无法写入 tmp 可能还有其他可能的解释:例如该目录未添加到 open_basedir directive, or that somehow the directory immutable attribute got set/tmp 不太可能)。但在任何这些情况下,您都会收到一条错误消息。