PHP 要呼叫 Shell 執行程式的時候, 偷懶有 `ls` 可以使用, 不過, 正規點可以使用 system()、exec()、shell_exec() 這三個 Function 來操作.
PHP system()、exec()、shell_exec() 的 差異
system()、exec()、shell_exec() 官方文件說明如下:
system — Execute an external program and display the output
string system ( string $command [, int &$return_var ] )
exec — Execute an external program
string exec ( string $command [, array &$output [, int &$return_var ]] )
shell_exec — Execute command via shell and return the complete output as a string
string shell_exec ( string $cmd )
一般系統會有兩種輸出, 一種是系統狀態(return code), 一種是輸出文字(output string), 這三個 Function 主要就是這些回傳的差異.
system()
$last_line = system('ls', $return_var);
system() 會將輸出內容直接印出, 所以若於網頁, 會將所有回傳內容都顯示於頁面上.
$last_line: 只能取得最後一行的內容
$return_var: 取得系統狀態回傳碼
exec()
exec('ls', $output, $return_var);
$output: 回傳內容都會存於此變數中(儲存成陣列), 不會直接秀在頁面上.
$return_var: 取得系統狀態回傳碼
shell_exec()
$output = shell_exec('ls');
$output: 回傳內容都會存於此變數中(儲存成純文字內容), 不會直接秀在頁面上.
範例程式
由此範例執行一次就比較容易理解. (請建立一個目錄, 隨便放兩個檔案, 再將此程式放置執行)
echo "\nsystem";
$last_line = system('ls', $return_var);
echo "\nreturn_var:";
print_r($return_var);
echo "\nlast_line:";
print_r($last_line);
echo "\n\nexec";
exec('ls', $output, $return_var);
echo "\nreturn_var:";
print_r($return_var);
echo "\noutput:";
print_r($output);
echo "\n\nshell_exec";
$output = shell_exec('ls');
echo "\noutput:";
print_r($output);
?>
相關
作者: Tsung
對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.檢視「Tsung」的全部文章