簡體   English   中英

PHP腳本無法通過電子郵件管道寫入文件

[英]PHP script can not write to file with email piping

我編寫了一個簡單的腳本來處理收到的電子郵件。 這是經過測試的方案:

A.腳本功能是發送電子郵件,指示已通過管道地址接收到電子郵件。

經過瀏覽器測試-成功

通過CLI測試-成功

經過管道測試-成功

B.腳本功能是解析文件並將文件寫入文件夾,並發送電子郵件,指示已通過管道地址接收到電子郵件

-由瀏覽器測試-寫入文件和發送電子郵件。

通過CLI測試-寫入文件和發送電子郵件。

-通過管道測試-未寫入文件,但發送了電子郵件。

我已將腳本簡化為讀取和寫入管道消息的基本功能。 我懷疑該問題是許可問題,但是我找不到任何支持證據。

我不太會使用CLI,但是可以執行某些任務。 我不確定要在何處查找管道方案的日志文件。

管道在所有測試的情況下都可以正常工作。 這是簡化的代碼,當通過管道調用時失敗:

#!/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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM