2011-04-29 154 views
1

我执行下面的命令来使数据库备份:PHP:如何获取失败的shell命令的错误信息?

$exec = exec("mysqldump --opt 
         --user=$database_user 
         --password=$database_pass 
         --host=$database_host 
         $database_name > $output_filename", $out, $status); 

要检查是否mysqldump失败我做的:

if ($status == 0) { 
    // OK 
} else { 
    // Error 
    // How could I print the error message here ? 
} 

万一出了差错和mysqldump失败了,我怎么可能得到错误信息 ?

回答

2

您可以使用proc_open(也是Emil建议的)。下面是如何实现你想要的更完整的例子。

$exec_command = "mysqldump --opt 
        --user=$database_user 
        --password=$database_pass 
        --host=$database_host 
        $database_name" 

$descriptorspec = array(
         0 => array("pipe", "r"), // stdin pipe 
         1 => array("file", $output_filename, "w"), // stdout to file 
         2 => array("pipe", "w") // stderr pipe 
); 

$proc = proc_open($exec_command, $descriptorspec, $pipes); 

fwrite($pipes[0], $input); //writing to std_in 
fclose($pipes[0]); 

$err_string = stream_get_contents($pipes[2]); //reading from std_err 
fclose($pipes[2]); 

$return_val = proc_close($proc); 

编辑:

改变的输出写如果使用了shell_exec到文件

+0

非常感谢! – 2011-04-29 14:23:44

1

如果您想阅读stderr,则需要使用proc_open。手册中的示例应该能够帮助您。

+0

或重定向到标准输出并从'$ output_filename'中提取它,因为无论如何转储错误都无效。 – 2011-04-29 12:18:53

+0

@Marc:我怎么能这样做?你能显示命令吗? – 2011-04-29 12:26:37

+0

'2>&1'将stderr(按照惯例,filehandle#2)重定向到标准输出(文件句柄#1) – 2011-04-29 15:55:35

0

,追加2> & 1到命令,它将STDERR重定向到STDOUT。

相关问题