Using set_time_limit() or max_execution_time, does not “really” limits (except on Windows) the execution time, because as stated in PHP manual:
Note:
The set_time_limit() function and the configuration directive
max_execution_time only affect the execution time of the script
itself. Any time spent on activity that happens outside the execution
of the script such as system calls using system(), stream operations,
database queries, etc. is not included when determining the maximum
time that the script has been running. This is not true on Windows
where the measured time is real.
A solution is proposed in PHP comments to have a “real” execution time limit like what I’m looking for, but I found it unclear/confusing.
I might be wrong, but as far as I understand you ask for explanation of the “PHP comments” solution code.
The trick is to spawn a child process, using pcntl_fork function, which will terminate the original (parent) process after some timeout. Function pcntl_fork returns process id of newly created child process inside a parent process execution thread and zero inside child process execution thread. That means parent process will execute the code under if statement and the child process will execute code under else. And as we can see from the code, the parent process will perform endless loop while child process will wait 5 seconds and then kill his parent. So basically you want to do something like this:
I hope I’ve exlained it well. Let me know if you sill have question regarding this solution.