background top

Command line, PHP & background processing

PHP Command Line Interpreter

Recently I encountered a situation where I need to run a PHP script in the background. A client requested a YouTube like application where the users can upload a video and it will automatically create a preview FLV flash version. The conversion was to be handled by FFMPEG, an open source piece of software to convert a huge range of audio and video formats.

In order to better get a handle on FFMPEG I downloaded the PHPVideoToolkit. The toolkit abstracts FFMPEG into a PHP class for easier manipulation. I created a script that would use the PHPVideoToolkit to convert the video files into FLV format.

Here is the snag: PHP will not finish executing the script until FFMPEG has finished the conversion. For longer files the browser can sit in it’s “thinking” mode for quite some time until the conversion is finished. This was unacceptable for the situation we were looking where it was unrealistic to expect users to sit there and wait for the entire conversion to take place before they could move on. There needed to be some way to do this as a background process.

exec()

Enter the exec command. This command allows us to run any program that can be run from the command line. The reason we use exec() instead of say passthru(), which also runs the command line, is that with exec() we can specify to take the content of the output buffer and send them to a file. Passthru returns the output right away to the browser. That’s fine if we wanted to run FFMPEG with the super long cryptic command line. How do we do this with our PHPVideoToolkit class though?

php cli

Enter the php command line interpreter (cli). The php command line interpreter allows you to run any php script from the command line.

Now we can create a simple script that uses the PHPVideoToolkit to run FFMPEG. Then we use exec() to run this php script from the command line as a background process.

exec('php convert.php >> convert.log &');

It took me a bit to figure this out as I’m not really a hardcore Linux guy. So here’s the breakdown of the command:

  • “php” - invokes the php command line interpreter
  • “convert.php” - the name of the php script to run
  • “>>” - this specifies where to direct the output buffer. Use ‘>’ to create a new file as opposed to ‘>>’ to append to an existing file.
  • “convert.log” - name of the file where output will be directed. You can use “/dev/null” if you want to send the output into a virtual black hole.
  • “&” - this is to run the command as a background process

PHP becomes far more versatile when we can run external programs for specific tasks. Allowing us to run them in the background can help to give the user a better experience.

Leave a Reply