在 WAMP 等集成環境中,需修改 php.ini:
safe_mode = Off ; 從 disable_functions 移除 exec, system, shell_exec, passthru, popen, proc_open disable_functions =
重啟 Apache 生效。
| 函數 | 返回值 | 適用場景 | 獲取輸出方式 |
|---|---|---|---|
exec() | 最後一行輸出 | 需獲取返回碼、逐行處理輸出 | 第二參數 &$output 數組 |
system() | 最後一行輸出 | 直接輸出到瀏覽器、需返回碼 | 第二參數 &$return_var |
shell_exec() | 完整輸出字符串 | 需獲取完整輸出、無需返回碼 | 直接返回 |
passthru() | 無 | 二進制輸出(圖片/PDF) | 直接輸出 |
exec('convert a.jpg b.jpg 2>&1', $output, $return_val);
print_r($output); // 包含 stderr 輸出
2>&1 將標準錯誤重定向到標準輸出,避免靜默失敗。
// Windows
exec("start /B php long_task.php > nul 2>&1");
// Linux
exec("php long_task.php > /dev/null 2>&1 &");
escapeshellcmd() (命令本身) 和 escapeshellarg() (參數)。/usr/bin/convert,或設置 PATH。set_time_limit() 或使用非阻塞模式。iconv('GBK', 'UTF-8', $output) 轉換。