开发者

PHP: How to get the error message of failed shell command?

I execute the following command to make a database backup:

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

To check if mysqldump failed I do:

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

In case 开发者_运维知识库something goes wrong and mysqldump fails, how could I get the error message ?


You can use proc_open (as also suggested by Emil). below is a somewhat more complete example of how to achieve what you want.

$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);

EDIT:

changed output to write to file


You'll need to use proc_open if you want to read stderr. The example in the manual should get you going.


If you are using shell_exec, append 2>&1 to the command, it will redirect STDERR to STDOUT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜