| 特性 | exec() | shell_exec() |
|---|---|---|
| 返回值 | 最後一行輸出(字串) | 完整輸出(字串,含換行) |
| 輸出參數 | 第二參數接收完整輸出陣列 | 無(直接返回完整字串) |
| 返回碼 | 第三參數接收退出碼 | 無法獲取 |
| 適用場景 | 單行結果、需獲取退出碼 | 多行結果、完整日誌輸出 |
# 目錄結構 -rw-rw-r--. 1 www web 133 7月 16 15:00 a.php -rw-r--r--. 1 lee web 59 2月 29 17:05 b.php -rw-r--r--. 1 lee web 81 3月 8 17:00 c.php
<?php
$data = exec('/bin/ls -l');
echo '<pre>';
print_r($data);
echo '</pre>';
?>
輸出:
-rw-r--r--. 1 lee web 81 Mar 8 17:00 c.php
僅返回最後一行。
<?php
$data = shell_exec('/bin/ls -l');
echo '<pre>';
print_r($data);
echo '</pre>';
?>
輸出:
total 12 -rw-rw-r--. 1 www web 139 Jul 16 2012 a.php -rw-r--r--. 1 lee web 59 Feb 29 17:05 b.php -rw-r--r--. 1 lee web 81 Mar 8 17:00 c.php
返回完整輸出,含 total 統計行。
<?php
$output = [];
$return_code = 0;
$last_line = exec('/bin/ls -l', $output, $return_code);
echo "最後一行: $last_line\n";
echo "退出碼: $return_code\n";
echo "完整輸出:\n";
print_r($output);
?>
escapeshellarg()、escapeshellcmd()php.ini 中 disable_functions = exec,shell_exec,system,passthru,popen,proc_openshell_exec()exec() + 第三參數popen() 流式讀取理解這兩個函式的本質差異,能避免「明明命令正確卻拿不到預期結果」的常見坑。