提到 PHP,多數開發者聯想到的是動態網頁開發。鮮為人知的是,PHP 同樣是一門優秀的 Shell 腳本語言。雖然功能豐富度不及 Perl 或 Bash,但對於熟悉 PHP 語法的開發者而言,它能大幅降低學習曲線,快速構建自動化維護腳本、資料處理工具或系統管理任務。
要將 PHP 作為命令列工具使用,必須在編譯時選擇 CGI 二進制模式(而非 Apache 模組):
./configure --enable-cli --disable-cgi # 現代 PHP 直接支援 --enable-cli
make && make install
編譯後的執行檔通常位於 /usr/local/bin/php。安全提醒:CGI 模式需妥善設定 open_basedir、disable_functions 等指令防範風險,詳見 PHP 官方手冊。
腳本首行需宣告解譯器路徑,並加入 -q 參數抑制 HTTP Header 輸出:
#!/usr/local/bin/php -q
<?php
// 這裡撰寫您的 PHP 邏輯
?>
PHP 自動將參數填入 $argv 陣列($argv[0] 為腳本檔名),$argc 為參數總數:
<?php
if ($argc < 3) {
die("Usage: {$argv[0]} FIRST_NAME LAST_NAME\n");
}
$first = $argv[1];
$last = $argv[2];
printf("Hello, %s %s! How are you today?\n", $first, $last);
?>
執行:php script.php Darrell Brogdon → 輸出 Hello, Darrell Brogdon! How are you today?
注意:Web 模式下$argv[1]對應 Query String 首參數,CLI 模式下$argv[0]為檔名,兩者索引差異請務必區分。
PHP 無內建讀取 STDIN 的高階函式,需自行封裝(Linux/Unix 適用):
function read(): string {
$fp = fopen('php://stdin', 'r');
$input = fgets($fp, 255);
fclose($fp);
return rtrim($input, "\n\r"); // 移除尾部換行符
}
// 使用範例
print("What is your first name? ");
$first = read();
print("What is your last name? ");
$last = read();
print("\nHello, $first $last! Nice to meet you!\n");
關鍵點:fgets() 會保留換行符,必須用 rtrim() 或 chop() 清理,否則字串拼接會出現多餘空行。
在 Bash 腳本中內嵌 PHP 程式碼:
#!/bin/bash
echo "This is the Bash section."
/usr/local/bin/php -q << 'EOF'
<?php
\$myVar = 'PHP'; // 必須轉義 $ 避免 Bash 先行解析
print("This is the \$myVar section of the code\n");
?>
EOF
陷阱警示:若未轉義\$myVar,Bash 會嘗試替換自身變數導致 PHP 語法錯誤(Parse error)。使用單引號'EOF'可完全禁用變數展開,更安全。
cron 定期執行資料庫備份、日誌切割、快取清理。declare(strict_types=1); 嚴格模式。php://stdin、php://stdout、php://stderr 流包裝器處理 I/O。fwrite(STDERR, "Error: $msg\n");。exit(0) 成功、exit(1) 失敗,便於 Shell 判斷。getopt() 解析長/短選項(如 -v、--verbose)。PHP CLI 讓您以熟悉的語法處理系統層級任務,無需在多種語言間切換上下文。掌握參數處理、互動輸入、嵌入技巧與最佳實踐,即可將 PHP 打造為得心應手的自動化利器。