PHP 项目,线上碰到个奇怪问题,使用fwrite
写入tmpfile()
失败。这里的失败并不是指fwrite
返回 FALSE
,而是返回int(0)
,写入 0 个字节。代码很简单如下所示:
$f = tmpfile();
$length = fwrite($f, '123');
var_dump($length);
通过浏览器访问,即php-fpm
方式下,输出 int(0)
。我做了其他几种情况的测试:
命令行环境:代码原封不动,执行是可以成功写入的。
php-fpm 浏览器访问
:将tmpfile()
替换成fopen('非 /tmp 目录', 'w+')
,php-fpm
下可以写入,输出int(3)
php-fpm 浏览器访问
:将tmpfile()
替换成fopen('/temp/test-randomstring', 'w+')
,输出int(0)
当前问题已经通过其他迂回方式解决,但是为何写入失败还没有查出原因。最初是怀疑跟服务器的磁盘剩余空间有关(仅剩 10M),但是 1 2 两次测试说明 10M 应该是够用的。
请问大家有什么好的查 BUG 思路?或碰到过类似问题?
更新, 新增了一段测试代码
$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(file_get_contents('/tmp/'.$name.'.txt'));
命令行执行,文件写入正常。 php-fpm
跑的时候,文件始终写入 0 字节,但文件是创建成功了的
Php has its own /tmp in /tmp/systemd-private-nABCDE/tmp when accessed through nginx
Because systemd is configured to give nginx a private /tmp. If you must use the system /tmp instead for some reason then you will need to modify the .service file to read "PrivateTmp=no".
detail can see on stackoverflow question