Tygo
Tygo

Reputation: 192

Continue php after page closed exec() ffmpeg

I am wondering how I can continue a php page after exec() (ffmpeg) and the page has been closed.

I have a form that allows people to convert their video files with ffmpeg but if the user clicks away the page the exec() keeps going but anything after this exec is not being executed.

<?php
   if (!empty($_POST) && $imgDir) {
      exec('"/dir/to/ffmpeg" -f image2 -i "' . $imgDir . '" -r 12 -s 610x489 /dir/to/out.avi', $out);

      /* INSERT statement (Not being executed) */
      $sql = "INSERT INTO requests (userID,image) VALUES (?,?)";
      $stmt= $pdo->prepare($sql);
      $stmt->execute([$user_id, $imgDir]);
   }
?>

I want a user to be able to click an away the page, so they don't have to wait and can download their file later.

Upvotes: 1

Views: 241

Answers (2)

Pinke Helga
Pinke Helga

Reputation: 6702

If you want to start this command from PHP in the background, you can run non-blocking processes by this pattern:

if(is_resource($proc = proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes)))
{
    stream_set_blocking($pipes[1], false);
    stream_set_blocking($pipes[2], false);

On a Linux system you can start a command with a prepended nohup, e.g.

$cmd = 'nohup "/dir/to/ffmpeg" -f image2 -i "' . $imgDir . '" -r 12 -s 610x489 /dir/to/out.avi'

After using nohup you can even exit the process which started the new process. It will be detached from parent process.

Upvotes: 1

ADyson
ADyson

Reputation: 62008

A common solution in this type of scenario is to offload the conversion process to a background script (e.g. a job triggered regularly by cron). This avoids problems with long-running processes timing out, or issues with external command-line processes not returning correctly.

The web page would just put a request into a queue (e.g. in a db table) and save the file.

The background service would then pick the next item off the queue, process it, and mark it complete.

Then you have to consider how to notify the user. You could email them, or have a status page where they can check their jobs and download any files that are ready, or both, or some other process of your choosing. Perhaps you can allow the user to specify how they want to be informed.

Upvotes: 1

Related Questions