Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 命令列執行 PHP 檔案並傳遞參數完整教學:$argv/$argc 實戰範例

編輯:關於 Linux

在 CLI 模式下執行 PHP 腳本時,無法使用 `$_GET`/`$_POST` 等超全域變數接收參數。正確做法是透過 $argv 陣列與 $argc 變數取得命令列引數。本文詳細說明參數傳遞機制、常見錯誤與實戰範例。

PHP CLI 參數傳遞示意圖

常見錯誤示範

# 錯誤:嘗試用 URL 查詢字串方式傳參
php /path/script.php?lang=en
# 輸出:Could not open input file: /path/script.php?lang=en

CLI 模式不經過 Web Server,無 HTTP 協定,故查詢字串無效。

正確作法:使用 $argv / $argc

  • $argv:包含所有引數的陣列,$argv[0] 為腳本檔名
  • $argc:引數總數 (含檔名)

實戰測試腳本 test.php

執行與輸出範例

$ php test.php 111 222 333 444
All param is:
Array
(
    [0] => test.php
    [1] => 111
    [2] => 222
    [3] => 333
    [4] => 444
)
Total number of parameter is: 5

進階應用:解析具名參數

$ php script.php --lang=zh_TW --env=staging --debug
Language: zh_TW
Environment: staging
Debug: true

與 Shell Script 比較

特性PHP CLIShell Script
參數存取 $argv 陣列 $1, $2... 位置參數
參數總數 $argc $#
腳本名稱 $argv[0] $0
具名參數解析 getopt() getopts / 手動解析

最佳實踐建議

  • 腳本開頭加上 #!/usr/bin/php 並賦予執行權限 (chmod +x),可直接 ./script.php arg1 arg2 執行。
  • 使用 getopt() 處理長/短選項,提升腳本易用性。
  • 錯誤訊息輸出至 STDERR:fwrite(STDERR, "Error msg\n");
  • 回傳結束碼:exit(1); 非零值表示失敗,利於腳本串聯判斷。

掌握 $argv/$argc 與 getopt(),即能編寫健壯、可攜的 PHP CLI 工具腳本。

Copyright © Windows教程網 All Rights Reserved