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.
2 Answers
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");
?>
3 Comments
php_nub_qq
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?
Dave Chen
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'.php_nub_qq
Thanks! I will do some extra researching on bash files ^^
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();
header('Connection: Close');.