阅读量:114
在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()函数可能会带来安全风险,因为它允许执行外部命令。确保在执行外部命令之前对用户输入进行充分的验证和过滤,以防止潜在的安全漏洞。