2011-04-29 149 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。

相關問題