PHP 不只能跑在網頁伺服器,也是優秀的命令列腳本語言。掌握 CLI 模式可編寫定時任務、資料遷移、佇列消費者、部署腳本等自動化工具。
# 1. 直接執行腳本檔案
php script.php arg1 arg2
# 2. 執行單行程式碼 (-r,無需 標籤)
php -r "echo 'Hello ' . $argv[1];" World
# 3. 逐行處理標準輸入 (-R)
echo -e "line1\nline2" | php -R "echo '$argn\n';"
# 4. 互動模式 (-a)
php -a
<?php
// cli_args.php
echo "參數總數 (argc) = {$argc}\n";
echo "參數陣列 (argv) = \n";
print_r($argv);
/*
執行:php cli_args.php id name sex
輸出:
參數總數 (argc) = 4
參數陣列 (argv) =
Array
(
[0] => cli_args.php
[1] => id
[2] => name
[3] => sex
)
*/
$argv[0] 永遠是腳本檔名$argc 包含檔名在內的總數$_SERVER| 選項 | 說明 |
|---|---|
-r | 直接執行程式碼字串 |
-f | 指定執行檔案 (可省略) |
-l | 語法檢查 (lint),不執行 |
-i | 顯示 phpinfo() |
-m | 列出已載入模組 |
-v | 顯示版本資訊 |
-c | 指定 php.ini 路徑 |
-d | 覆蓋 ini 設定 (如 -d memory_limit=512M) |
-R | 對 STDIN 每行執行程式碼 ($argn=當前行, $argi=行號) |
-F | 對 STDIN 每行執行檔案 |
-B | 處理 STDIN 前先執行程式碼 |
-E | 處理 STDIN 後執行程式碼 |
-S | 內建 Web 伺服器 (PHP 5.4+) |
<?php
// 讀取 STDIN (管道輸入)
$stdin = fopen('php://stdin', 'r');
while (($line = fgets($stdin)) !== false) {
echo "讀到: " . trim($line) . "\n";
}
fclose($stdin);
// 寫入 STDOUT (正常輸出)
fwrite(STDOUT, "正常訊息\n");
// 寫入 STDERR (錯誤輸出,可分流導向檔案)
fwrite(STDERR, "錯誤訊息\n");
<?php
// rename.php
// 用法:php rename.php /path/to/dir "prefix_" ".bak"
if ($argc < 4) {
fwrite(STDERR, "用法: php {$argv[0]} 目錄 前綴 後綴\n");
exit(1);
}
[$script, $dir, $prefix, $suffix] = $argv;
if (!is_dir($dir)) {
fwrite(STDERR, "目錄不存在: $dir\n");
exit(1);
}
$count = 0;
$files = new FilesystemIterator($dir);
foreach ($files as $file) {
if ($file->isFile()) {
$new_name = $prefix . $file->getBasename() . $suffix;
$new_path = $file->getPath() . '/' . $new_name;
if (rename($file->getPathname(), $new_path)) {
echo "重命名: {$file->getFilename()} -> $new_name\n";
$count++;
}
}
}
echo "完成,共重命名 $count 個檔案。\n";
<?php
// 短選項: -f -v -- 表示必須參數
// 長選項: --file= --verbose --
$options = getopt('f:v::', ['file:', 'verbose::', 'help']);
if (isset($options['h']) || isset($options['help'])) {
echo "用法: php script.php -f <檔案> [--verbose]\n";
exit;
}
$file = $options['f'] ?? $options['file'] ?? null;
$verbose = isset($options['v']) || isset($options['verbose']);
if (!$file) {
fwrite(STDERR, "錯誤: 必須指定 -f 檔案\n");
exit(1);
}
echo "處理檔案: $file\n";
if ($verbose) echo "詳細模式開啟\n";
#!/usr/bin/env php,加上 chmod +x script.php 可直接執行composer require symfony/console 建構專業等級 CLI 應用php-cli.ini 獨立配置(如關閉 display_errors、調大 memory_limit)