4

I need to run a second php file in the background. The problem is that this file needs to only run 20 seconds after the current file has completed. I have used exec("php test_script.php") to run the file but I cant get it to wait. If I use sleep() if halts my current script.

To be a bit more specific. I am uploading a file to a remote server. I then need to wait approximately 20 seconds after completing the upload to check the server for a response. In the meantime I would like to carry on with the current file. The second file will do what is needed in the background. At the moment I have to wait then run the second file.

user1097983
  • 43
  • 1
  • 3

2 Answers2

6

The simplest solution to this can be found here. Basically, execute your script like this:

exec('test_script.php >/tmp/output.txt &');

Notice the ampersand ('&') at the end, this will make the command run in the background! You can delay the script by 20 seconds by adding the sleep in test_script.php.

Your other options are to trigger the second script either via Javascript (AJAX) from client side; or have a process running in the background (or regularly via cron job) which is checking some kind of common data (e.g. database) for requests, and which will get active if such a request needs to be processed.

JavaScript is not an option if the script has to run, since the user could decide to navigate away from your page, or not be executing JavaScript, or be malicious and decide just not do execute that particular JavaScript.

Community
  • 1
  • 1
codeling
  • 11,056
  • 4
  • 42
  • 71
2

Put the sleep() call in your test_script.php file (before the actual code) and then when calling exec, make sure to redirect the output of the command to a file. Something like:

exec("php test_script.php > /tmp/output.txt");

This assures you that it won't interrupt the loading of the first (calling) script and it will be asynchronous.

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • How will just redirecting the output make the process be execute asynchronously / in the background? – codeling Dec 14 '11 at 14:40
  • @nyarlathotep - according to the PHP manual: "If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends." – jason Dec 14 '11 at 14:47
  • Interesting, the german php manual version (which for me turns up first on google) doesn't have this additional remark... – codeling Dec 14 '11 at 14:52
  • additionally, however, the solutions I have seen usually also need the ampersand (&) – codeling Dec 14 '11 at 15:07
  • 1
    @nyarlathotep they don't *need* it, but it's good practice to put it there. – Eduard Luca Dec 15 '11 at 10:16