正确的方法来捕获php exec中的imagemagick转换错误

时间:2014-05-22 12:17:33

标签: php error-handling imagemagick

大家好,我们在php exec()中捕捉imagemagick转换错误的正确方法是什么?

exec('convert img.jpg -resize 100x100 img.jpg',$output);
var_dump($output);

$output始终返回一个空白数组。

1 个答案:

答案 0 :(得分:2)

对于exec,评估返回状态;这是第三个参数。

exec('convert img.jpg -resize 100x100 img.jpg',$output,$exit_status);
if( $exit_status !== 0 ) {
  // Error handle here
}

但是,写入的任何内容都可能不会出现在$output数组中。更好,更灵活的方法是使用proc_open&管道

$pipe_handle = array();
$pipe_spec = array(
  array('pipe','r'), // stdin
  array('pipe','w'), // stdout
  array('pipe','w')  // stderr
);

$pid = proc_open('convert img.jpg -resize 100x100 img.jpg',$pipe_spec,$pipe_handle);
// Close stdin
fclose($pipe_handle[0]);
// Read what's in stdout buffer & close
$pipe_stdout = stream_get_contents($pipe_handle[1]);
fclose($pipe_handle[1);
// Read what's in stderr buffer & close
$pipe_stderr = stream_get_contents($pipe_handle[2]);
fclose($pipe_handle[2]);

// Get exist status
$exit_status = proc_close($pid);

if( $exit_status === -1 ) {
  // Handle error and evaluate stderr
} else {
  // Handle success and evaluate stdout
}

更多工作,但可以从正常消息(如果有)中清楚地分离错误