I have a command-line PHP script that runs a wget request using each member of an array with foreach. This wget request can sometimes take a long time so I want to be able to set a timeout for killing the script if it goes past 15 seconds for example. I have PHP safemode disabled and tried set_time_limit(15) early in the script, however it continues indefinitely. Update: Thanks to Dor for pointing out this is because set_time_limit() does not respect system() calls.
So I was trying to find other ways to kill the script after 15 seconds of execution. However, I'm not sure if it's possible to check the time a script has been running while it's in the middle of a wget request at the same time (a do while loop did not work). Maybe fork a process with a timer and set it to kill the parent after a set amount of time?
Thanks for any tips!
Update: Below is my relevant code. $url is passed from the command-line and is an array of multiple URLs (sorry for not posting this initially):
foreach( $url as $key => $value){
$wget = "wget -r -H -nd -l 999 $value";
system($wget);
}
You can direct the output of the wget program to a file, which then returns immediately.
Also see:
Source: set_time_limit() @ php.net
I think the far best way is to handle the killing in the command itself, at least on Linux (Ubuntu 17.10). No other means worked for me...
proc_terminate
from another answer worked but no output would be given.In the example below, I adding a magic string that checks if your process is still running. If running longer than
$sec
, it kills the process immediately, leaving a note 'Timeout!'.Like this, I am sure the command won't exceed timeout and I receive all the stdout/stderr I need.
Try using the wget command line argument
--timeout
in addition toset_time_limit()
.Keep in mind
set_time_limit(15)
restarts the timeout counter from zero so don't call it inside a loop (for your purpose)from
man wget
:EDIT: OK. I see what you're doing now. What you should probably do is use proc_open instead of
system
, and use thetime()
function to check the time, calling proc_terminate if wget tskes too long.You can use a combination of "--timeout" and time(). Start off by figuring out how much time you have total, and lower the --timeout as your script runs.
For example:
Note: if you don't use -t, wget will try 20 times, each waiting --timeout seconds.
Here's some example code using proc_open/proc_terminate (@Josh's suggestion):