Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PHP from command line

I am trying to manage a queue of files waiting to be processed by ffmpeg. A page is run using CRON that runs through a database of files waiting to be processed. The page then builds the commands and sends them to the command line using exec().

However, when the PHP page is run from the command line or CRON, it runs the exec() OK, but does not return to the PHP page to continue updating the database and other functions.

Example:

<?php
$cmd = "ffmpeg inpupt.mpg output.m4v";

exec($cmd . ' 2>&1', $output, $return);

//Page continues...but not executed
$update = mysql_query("UPDATE.....");
?>

When this page is run from the command line, the command is run using exec() but then the rest of the page is not executed. I think the problem may be that I am running a command using exec() in a page run from the command line.

Is it possible to run a PHP page in full from the command line which includes exec()?

Or is there a better way of doing this?

Thank you.

like image 515
Kit Avatar asked Apr 13 '11 08:04

Kit


People also ask

What is PHP CLI command?

As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.

How do I access PHP shell?

The CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1. 0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly.


2 Answers

I wrote an article about Running a Background Process from PHP on Linux some time ago:

<?php system( 'sh test.sh >/dev/null &' ); ?>

Notice the & operator at the end. This starts a process that returns control to the shell immediately AND CONTINUES TO RUN in the background.

More examples:

<!--
    saving standard output to a file
    very important when your process runs in background
    as this is the only way the process can error/success
-->
<?php system( 'sh test.sh >test-out.txt &' ); ?>
<!--
    saving standard output and standard error to files
    same as above, most programs log errors to standard error hence its better to capture both
-->
<?php system( 'sh test.sh >test-out.txt 2>test-err.txt &' ); ?>
like image 73
Salman A Avatar answered Oct 04 '22 22:10

Salman A


Have you tried using CURL instead?

like image 33
wilsonpage Avatar answered Oct 04 '22 20:10

wilsonpage