Joe
Joe

Reputation: 8292

Proper way to catch imagemagick convert errors in php exec

Hi guys whats the proper way to catch imagemagick convert errors in php exec()?

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

$output always return a blank array.

Upvotes: 1

Views: 1070

Answers (1)

emcconville
emcconville

Reputation: 24439

For exec, evaluate the return status; which is the third parameter.

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

However, anything written to may not be present in the $output array. A better, more flexible, approach would be to use proc_open & pipes.

$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
}

A bit more work, but can cleanly seperate errors from normal messages (if any)

Upvotes: 2

Related Questions