0

So I read throug this article: https://trac.ffmpeg.org/wiki/PHP and found this:

<?php
echo "Starting ffmpeg...\n\n";
echo shell_exec("ffmpeg -i input.avi output.avi >/dev/null 2>/dev/null &");
echo "Done.\n";

the code works almost perfectly fine, but the only thing that bothers me is, that because the shell_exec is being executed in the background (so there is no loading sign on the tab the whole time) all the echo's are being executed immediatly. This means, that the "Done" echo is being written before ffmpeg finished its task.

But when I remove the '&' the site does also what it is intended to do but now it waits until the shell_exec is finished until it echo's out the "Starting ffmpeg..."

So I kinda have the problem of figuring out how to get to such an order:

1) echo something 2) execute commad and wait until its finished. 3) echo again

I am a total beginner to php but have experience in programming overall. Please have mercy.

Thank you for your time!

userlip
  • 79
  • 1
  • 2
  • 11
  • 2
    Using the & at the end of a command will immediately return (and run the process in the background) Thats why the page loads and shows the final echo statement before the output of the command is complete. This answer gives a method to start the task without waiting for completion and also querying for progress on the conversion http://stackoverflow.com/a/6245461/2543650 – Legion Sep 14 '16 at 23:39

1 Answers1

1

You might want to use flush before you do your shell_exec. There are a few caveats to using this which are well explained in the php documentation page. Hope this helps.

<?php
  echo "Starting ffmpeg...\n\n";

  ob_flush();
  flush();
  echo shell_exec("ffmpeg -i input.avi output.avi >/dev/null 2>/dev/null");

  // a sleep could effectively be the same as your shell_exec operation
  // sleep(5);

  echo "Done.\n";
  ob_end_flush();
raj
  • 819
  • 5
  • 9
  • I used the flush(); function before my shell_exec.. It didnt help but thank you for your input! – userlip Sep 15 '16 at 01:24
  • did you also try the ob_flush() after the flush? – raj Sep 15 '16 at 01:29
  • I am sorry - I just overlooked your code and just saw the flush(); but didnt see the other ob_flushes! And it really worked! Unfortunately though my html code went away becuase of it. I am currently using my local Server in a vm and just some basic html with 1 button and 2 or 3 words but they seem to disappear now! The "starting ffmpeg" stands there now though. Still any suggestions about the html part? – userlip Sep 15 '16 at 02:24
  • Edit: Seems like the html stuff appeared again after my exec finished! Weird.... or not ? Edit 2.0: It only deleted the part below the script not the html part above, maybe that helps – userlip Sep 15 '16 at 02:33