首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 管道技術應用:popen 實現進程間通訊與郵件發送

     編輯:PHP 相關知識

Linux 管道 (|) 讓指令間直接傳遞資料。PHP popen() 開啟管道至外部命令,回傳檔案指標,可像操作檔案一樣讀寫。本文示範管道讀取命令輸出、發送郵件、常見參數與注意事項。

popen 基本語法

resource popen(string $command, string $mode); // mode: 'r' 讀取輸出, 'w' 寫入輸入
// 關閉:pclose($fp)

範例 1:讀取命令輸出 (ls -l)

<?php
$fp = popen('/bin/ls -l -FN /etc', 'r');
if ($fp) {
    while (!feof($fp)) {
        echo fgets($fp, 4096) . '<br>';
    }
    pclose($fp);
}
?>

範例 2:管道發送郵件 (sendmail)

比 Socket 簡單,無需手寫 SMTP 協定交握。

<?php
$fp = popen('/usr/sbin/sendmail -t', 'w'); // -t 從郵件標頭解析收件者
if ($fp) {
    $to = 'user@example.com';
    $subject = '測試郵件';
    $message = "Hello!\n這是管道發送的郵件。\n";
    $headers = "From: sender@example.com\r\n";
    $headers .= "Reply-To: sender@example.com\r\n";
    $headers .= "Subject: $subject\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";

    fwrite($fp, $headers . $message);
    fwrite($fp, "\n.\n"); // sendmail 結束標記
    pclose($fp);
    echo '郵件已送入佇列';
}
?>

管道 vs 重導向 vs Socket

方式特性適用場景
管道 popen雙向/單向資料流、類檔案操作、自動管理子進程命令輸出讀取、簡單郵件發送、過濾器鏈
重導向 exec() + > file單向、輸出至檔案、需自行讀檔長時間任務、需持久化輸出
Socket fsockopen/stream_socket_client完整 TCP 協定控制、需手寫應用層協定HTTP 請求、SMTP/IMAP/POP3、自定義協定

注意事項

  • popen 預設阻塞,大量輸出需考慮非阻塞或 proc_open。
  • 命令路徑請用絕對路徑 (如 /usr/sbin/sendmail) 確保可執行。
  • 輸入資料務必過濾,防止命令注入 (如 escapeshellarg、escapeshellcmd)。
  • Windows 環境 popen 行為不同,建議改用 proc_open 或 COM 組件。
  • 發送郵件生產環境建議使用 PHPMailer、SwiftMailer 或 Symfony Mailer,支援 SMTP、SSL、附件、佇列。

進階:proc_open 雙向管道

<?php
$descriptors = [
    0 => ['pipe', 'r'], // stdin
    1 => ['pipe', 'w'], // stdout
    2 => ['pipe', 'w'], // stderr
];
$proc = proc_open('/usr/bin/sort', $descriptors, $pipes);
if (is_resource($proc)) {
    fwrite($pipes[0], "c\na\nb\n");
    fclose($pipes[0]);
    echo stream_get_contents($pipes[1]); // a b c
    fclose($pipes[1]);
    proc_close($proc);
}
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved