What are some best practices for integrating external tools like ffmpeg with PHP for tasks like video conversion?

Integrating external tools like ffmpeg with PHP for tasks like video conversion requires using the shell_exec() function to execute ffmpeg commands. It is important to properly sanitize user input to prevent command injection attacks. Additionally, it is recommended to check for the existence of the ffmpeg executable before attempting to use it.

// Check if ffmpeg is installed
if (shell_exec('which ffmpeg') === null) {
    die('ffmpeg is not installed on this server');
}

// Sanitize input and construct ffmpeg command
$inputFile = escapeshellarg('input.mp4');
$outputFile = escapeshellarg('output.mp4');
$ffmpegCommand = "ffmpeg -i $inputFile $outputFile";

// Execute ffmpeg command
$output = shell_exec($ffmpegCommand);
echo $output;