0

I want to ask if anyone knows a way I can delay a php script without actually occupying a connection slot all the time. I am not completely aware of this but I was told that apache has a limit of connections or a limit of scripts running at the same time I can't exactly recall and this script of mine needs to run for about 1 to 3 hours and it doesn't really do anything heavy, it actually sleeps like 90% of the time.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • 2
    If you're updating stuff with a php script, either run it server side (no browser, just command line), or tell the php script to just run and exit (client shows blank screen and can close their browser). `header('Connection: Close');`. – Dave Chen May 25 '13 at 19:27
  • That's exactly the thing I was looking for! Thanks! – php_nub_qq May 25 '13 at 19:39
  • Possible duplicate of [close a connection early](http://stackoverflow.com/questions/138374/close-a-connection-early) – Eric Dubé Jun 16 '16 at 02:19

2 Answers2

1

If you're running a script and not expecting any response you can either run it in the terminal of the server computer with php "dir/to/php/script.php".

If the initialization of the script happens remotely then you could have the script exit so the script continues running but does not keep the connection alive. header('Connection: Close');

Example:

<?php

echo "The server is now doing some complex actions in the background..."; //even maybe a redirect instead
header('Connection: Close');
file_put_contents(file_get_contents("largest_file_in_the_world.txt"),"/tmp/test.txt");

?>
Dave Chen
  • 10,887
  • 8
  • 39
  • 67
  • That's exactly the thing I was looking for! Thanks! I just have one more question related to that. In case I decide I need to stop the script is there a way I can do this without restarting apache? – php_nub_qq May 25 '13 at 19:39
  • 1
    I recommend having `script.php` call a bash file that runs in the background. That way, you can later kill the bash file instead of killing apache. Example: `exec('nohup script.sh')` --> `php 'script.php'`. – Dave Chen May 25 '13 at 19:41
  • Thanks! I will do some extra researching on bash files ^^ – php_nub_qq May 25 '13 at 19:53
1

In addition, just sending the connection: close header wasn't enough, here's how the connection gets closed:

ignore_user_abort(true);
header("Connection: close", true);
header("Content-Length: 0", true);
ob_end_flush();
flush();
fastcgi_finish_request();

Source

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144