How can the exec() function in PHP be used to troubleshoot errors in external commands like Imagemagick?

To troubleshoot errors in external commands like Imagemagick using the exec() function in PHP, you can capture the output and error messages from the command by redirecting them to variables. This allows you to see any error messages or debug information that may help identify the issue.

$command = 'convert input.jpg -resize 50% output.jpg';
$output = array();
$return_var = 0;

exec($command . ' 2>&1', $output, $return_var);

if ($return_var !== 0) {
    // Handle error, display output for debugging
    echo "Error executing command: " . implode("\n", $output);
} else {
    // Command executed successfully
    echo "Command executed successfully";
}