Nalliappan
Nalliappan

Reputation: 1

Initiating background process for running php file as background from another php page

I want initiate one php page as background process from another php page.

Upvotes: 0

Views: 2167

Answers (3)

Luke Stevenson
Luke Stevenson

Reputation: 10341

This is a technique I used to get around restrictions applied by my webhost (who limited cronjobs to 15 minutes of execution time, so my backup scripts would always timeout).

exec( 'php somefile.php | /dev/null &' );

The breakdown of this line is:

  • exec() - PHP reference Runs the specified command, as if from the Linux Command Line.
  • php somefile.php: Invokes PHP to open, and run, somefile.php. This is the same behaviour as what would happen if that file was accessed through a web browser.
  • | ("pipe") - Sends the output of the proceeding command to a specified target. In this instance, it would "pipe" the content which would normally be read by the web browser accessing the file.
  • /dev/null - A blackhole. No, not kidding. It is a place where you send output if you just want it to disappear.
  • & - Appending this character to the end of a Linux command means "Do not wait - Send this to the background and continue."

So, in summary, the provided code will execute a PHP script, return no output, and not wait for it to finish before continuing onto the next line.

(And, as always, if any of these assumptions on my part are in error, I would love to be corrected by more knowledgeable members of the community.)

Upvotes: 2

Alex
Alex

Reputation: 34978

You have to make sure, that the background process is not terminated when the processing of the page finished. If you are on a Linux system, you could try to use the nohup command:

$command = 'nohup php somefile.php';
pclose(popen($command,'r'));

If it still gets terminated, you could try the "daemon" command.

Upvotes: 0

Nathan Osman
Nathan Osman

Reputation: 73195

Use popen():

$command = 'php somefile.php';
pclose(popen($command,'r'));

This launches somefile.php as a background process.

Upvotes: 3

Related Questions