在PHP中,使用exec()
函數執行外部命令時,可以通過將輸出重定向到文件來處理日志記錄
script.log
,用于存儲外部命令的輸出:$logFile = 'script.log';
exec()
函數執行外部命令,并將標準輸出和標準錯誤輸出重定向到日志文件:$command = 'your_command_here'; // 替換為你要執行的外部命令
exec($command . ' > ' . escapeshellarg($logFile) . ' 2>&1', $output, $return_var);
這里,$output
數組將包含外部命令的輸出,$return_var
變量將包含命令的返回狀態。
if ($return_var === 0) {
echo 'Command executed successfully.';
} else {
echo 'Command execution failed.';
}
file_get_contents()
函數讀取日志文件內容:$logContent = file_get_contents($logFile);
echo $logContent;
將以上代碼片段組合在一起,完整的示例如下:
<?php
$logFile = 'script.log';
$command = 'your_command_here'; // 替換為你要執行的外部命令
exec($command . ' > ' . escapeshellarg($logFile) . ' 2>&1', $output, $return_var);
if ($return_var === 0) {
echo 'Command executed successfully.';
} else {
echo 'Command execution failed.';
}
$logContent = file_get_contents($logFile);
echo $logContent;
?>
請注意,使用exec()
函數可能會帶來安全風險,因為它允許執行外部命令。確保在執行外部命令之前對用戶輸入進行充分的驗證和過濾,以防止潛在的安全漏洞。