hedhud
hedhud

Reputation: 73

Php Exec timeout

I have the following exec() command with an & sign at the end so the script runs in the background. However the script is not running in the background. It's timing out in the browser after exactly 5.6 minutes. Also if i close the browser the script doesn't keep running.

 exec("/usr/local/bin/php -q /home/user/somefile.php &")

If I run the script via the command line, it does not time out. My question is how do i prevent timeout. How do i run the script in the background using exec so it's not browser dependent. What am i doing wrong and what should i look at.

Upvotes: 0

Views: 7732

Answers (2)

Alain
Alain

Reputation: 36954

exec() function handle outputs from your executed program, so I suggest you to redirect outputs to /dev/null (a virtual writable file, that automatically loose every data you write in).

Try to run :

exec("/usr/local/bin/php -q /home/gooffers/somefile.php > /dev/null 2>&1 &");

Note : 2>&1 redirects error output to standard output, and > /dev/null redirects standard output to that virtual file.

If you have still difficulties, you can create a script that just execute other scripts. exec() follows a process when it is doing a task, but releases when the task is finished. if the executed script just executes another one, the task is very quick and exec is released the same way.

Let's see an implementation. Create a exec.php that contains :

<?php

  if (count($argv) == 1)
  {
    die('You must give a script to exec...');
  }
  array_shift($argv);
  $cmd = '/usr/local/bin/php -q';
  foreach ($argv as $arg)
  {
     $cmd .= " " . escapeshellarg($arg);
  }
  exec("{$cmd} > /dev/null 2>&1 &");

?>

Now, run the following command :

exec("/usr/local/bin/php -q exec.php /home/gooffers/somefile.php > /dev/null 2>&1 &");

If you have arguments, you can give them too :

exec("/usr/local/bin/php -q exec.php /home/gooffers/somefile.php x y z > /dev/null 2>&1 &");

Upvotes: 4

Christopher Armstrong
Christopher Armstrong

Reputation: 7953

You'll need to use shell_exec() instead:

shell_exec("/usr/local/bin/php -q /home/gooffers/somefile.php &");

That being said, if you have shell access, why don't you install this as a cronjob? I'm not sure why a PHP script is invoking another to run like this.

Upvotes: 1

Related Questions