Home  >  Article  >  Backend Development  >  奇怪问题 php-fpm 下使用 fwrite 写入 /tmp 目录失败

奇怪问题 php-fpm 下使用 fwrite 写入 /tmp 目录失败

WBOY
WBOYOriginal
2016-06-06 20:17:071752browse

PHP 项目,线上碰到个奇怪问题,使用fwrite写入tmpfile() 失败。这里的失败并不是指fwrite返回 FALSE,而是返回int(0),写入 0 个字节。代码很简单如下所示:

<code>$f = tmpfile();
$length = fwrite($f, '123');
var_dump($length);</code>

通过浏览器访问,即php-fpm方式下,输出 int(0)。我做了其他几种情况的测试:

  1. 命令行环境:代码原封不动,执行是可以成功写入的。

  2. php-fpm 浏览器访问:将 tmpfile() 替换成fopen('非 /tmp 目录', 'w+')php-fpm 下可以写入,输出 int(3)

  3. php-fpm 浏览器访问:将 tmpfile() 替换成 fopen('/temp/test-randomstring', 'w+'),输出 int(0)

当前问题已经通过其他迂回方式解决,但是为何写入失败还没有查出原因。最初是怀疑跟服务器的磁盘剩余空间有关(仅剩 10M),但是 1 2 两次测试说明 10M 应该是够用的。

请问大家有什么好的查 BUG 思路?或碰到过类似问题?


更新, 新增了一段测试代码

<code>$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'));</code>

命令行执行,文件写入正常。 php-fpm 跑的时候,文件始终写入 0 字节,但文件是创建成功了的

回复内容:

PHP 项目,线上碰到个奇怪问题,使用fwrite写入tmpfile() 失败。这里的失败并不是指fwrite返回 FALSE,而是返回int(0),写入 0 个字节。代码很简单如下所示:

<code>$f = tmpfile();
$length = fwrite($f, '123');
var_dump($length);</code>

通过浏览器访问,即php-fpm方式下,输出 int(0)。我做了其他几种情况的测试:

  1. 命令行环境:代码原封不动,执行是可以成功写入的。

  2. php-fpm 浏览器访问:将 tmpfile() 替换成fopen('非 /tmp 目录', 'w+')php-fpm 下可以写入,输出 int(3)

  3. php-fpm 浏览器访问:将 tmpfile() 替换成 fopen('/temp/test-randomstring', 'w+'),输出 int(0)

当前问题已经通过其他迂回方式解决,但是为何写入失败还没有查出原因。最初是怀疑跟服务器的磁盘剩余空间有关(仅剩 10M),但是 1 2 两次测试说明 10M 应该是够用的。

请问大家有什么好的查 BUG 思路?或碰到过类似问题?


更新, 新增了一段测试代码

<code>$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'));</code>

命令行执行,文件写入正常。 php-fpm 跑的时候,文件始终写入 0 字节,但文件是创建成功了的

权限
chmod 777 /tmp/test-randomstring
再试试可写就说明是权限问题

可以用chown改写文件拥有者,chmod再改为安全的权限。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn