PHP脚本不能写入带有邮件管道的文件


PHP script can not write to file with email piping

我编写了一个简单的脚本来处理收到的电子邮件。以下是经过测试的场景:

。脚本功能是发送一封电子邮件,表明在管道地址收到了电子邮件。

-通过浏览器测试-成功

-test by CLI - Success

-通过管道测试-成功

B。脚本功能是解析和写入文件到文件夹,并发送电子邮件,表明收到的电子邮件在管道地址

-浏览器测试-文件写入和电子邮件发送

-通过CLI测试-文件写入和邮件发送。

-测试管道-文件不写,但电子邮件发送。

我已经将脚本简化为读取和写入管道消息的基本功能。我怀疑是权限问题,但是我找不到任何支持的证据。

我的CLI不是很流利,但是可以完成一些任务。我不确定在哪里查找管道场景的日志文件。

Piping在所有测试场景中都工作得很好。下面是通过管道调用失败的简化代码:

#!/usr/bin/php -q
<?php
/* Read the message from STDIN */
$fd = fopen("php://stdin", "r"); 
$email = ""; // This will be the variable holding the data.
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
/* Saves the data into a file */
$fdw = fopen("/my/folder/mail.txt", "w");
fwrite($fdw, $email);
fclose($fdw);
/* Script End */

谢谢你的帮助。

修改代码为:

#!/usr/bin/php -q
<?php
/* Read the message from STDIN */
$email = file_get_contents('php://stdin');
/* Saves the data into a file */
$fdw = fopen("/Volumes/Cobra/Sites/email/mail.txt", "w+");
if (! $fdw) {
    error_log("Unable to open mail.txt for output.", 1, "myemail@mydomain.com", "From: admin@mydomain.com");
} else {
    fwrite($fdw, $email);
}
fclose($fdw);
/* Script End */

通过电子邮件发送错误消息。现在怎么办呢?管道调用的脚本以什么用户身份运行?

如果是权限问题,则fopen将在失败时返回FALSE。你没有检查这种情况,并假设一切正常。试着

$fd = fopen('php://stdin', 'r');
if (!$fd) {
   die("Unable to open stdin for input");
}
$fdw = fopen(...);
if (!$fdw) {
   die("Unable to open mail.txt for output");
}

如果die()都没有触发,那么就不是权限问题。

作为一种风格的东西,除非你的实际代码更复杂,并且确实想要处理大块的stdin,否则你可以这样做:

$email = file_get_contents('php://stdin');