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 腳本檔案:加入 Shebang 與賦予執行權限完整教學

編輯:關於 Linux

在 Linux 伺服器上撰寫 PHP 自動化腳本時,每次輸入 php script.php 顯得繁瑣。實際上只需在檔案首行加入 Shebang 指定 PHP 解釋器路徑,並賦予執行權限,即可像 Shell 腳本一樣直接執行。

建立可直接執行的 PHP 腳本

  1. 編寫腳本檔案 test_run.php:
#!/usr/bin/php
Here is some plain text.
Here is the file name:
  1. 賦予執行權限:
chmod u+x ./test_run.php
  1. 直接執行:
./test_run.php
# 輸出:
# Here is some plain text.
# Here is the file name:
# ./test_run.php

關鍵點說明

  • #!/usr/bin/php:Shebang 行,指定 PHP CLI 解釋器絕對路徑(可用 which php 確認)
  • chmod u+x:賦予檔案擁有者執行權限
  • $argv[0]:取得腳本檔案路徑(包含 ./ 前綴)
  • 腳本中可使用 $argv[1]、$argv[2]... 接收命令列參數

參考資源

PHP 官方文件:Command line usage - Example #2 Script intended to be run from command line

完成設定後,您可以將 PHP 腳本放入 /usr/local/bin 或加入 PATH 目錄,像系統指令一樣在任何路徑直接呼叫。

Copyright © Windows教程網 All Rights Reserved