後台執行php腳本
使用Linux系統搭建完整的PHP環境後,用戶常會遇到執行PHP腳本需要使用php myscript.php的方式,感覺較為繁瑣。實際上,Linux系統支持直接執行PHP腳本文件。具體操作步驟如下:
首先,編寫PHP腳本文件。例如,創建名為test_run.php的文件,內容如下:
Here is some plain text.
Here is the file name:
《?php
echo $argv[0], PHP_EOL;
》
腳本功能簡單,輸出當前腳本文件的名稱。
接著,通過命令執行腳本:
yuanyu@ymac:phpworkspace $ php test_run.php hello
輸出結果為:
Here is some plain text.
Here is the file name:
test_run.php
yuanyu@ymac:phpworkspace $
為腳本文件增加頭信息及設置許可權:
在文件首行添加php命令全路徑,前綴為#!:
#!/usr/bin/php
保持腳本內容不變:
《?php
echo $argv[0], PHP_EOL;
》
執行賦予可執行許可權:
yuanyu@ymac:phpworkspace $ chmod u+x 。/test_run.php
即可直接執行腳本:
yuanyu@ymac:phpworkspace $ 。/test_run.php
輸出結果為:
Here is some plain text.
Here is the file name:
/test_run.php
yuanyu@ymac:phpworkspace $
此方法在PHP官方文檔中亦有提及,請參考:
http://php.net/manual/en/features.commandline.usage.php
文檔中關於腳本在命令行運行的示例,請參照:
「Example #2 Script intended to be run from command line (script.php)」
❷ linux 如何關閉正在執行的php腳本
1. 如果不是後台執行,直接ctrl+c 就終止執行
2. 如果是後台執行
首先執行:sudo ps -ef|grep php
再次執行:sudo kill -9 pid 或者 sudo kill -15 pid
pid 為ps命令查處的進程號。