Home » Php » php – Set a timeout for a specific function / block of code (not the whole script)?

php – Set a timeout for a specific function / block of code (not the whole script)?

Posted by: admin July 12, 2020 Leave a comment


I have php scripts that call perl scripts to do various things and sometimes I get it where it just goes on and on without getting a response back, this is based on the variable that is being passed to the perl script and I am doing a lot of different ones in succession so I can’t get really debug it directly since I don’t have a response from perl…

I would really like to just be able to set a php function or block of code to timeout after a certain number of seconds.. I have been searching on this but haven’t found anything yet on how to do this,

I was thinking something like this could work but I don’t think it would dynamically update the $time variable, but maybe there is a way to get this to work? Any advice is appreciated

$time = time();
$timeout = $time + 5; //just as an example

do {

// do stuff
} while ($time < $timeout)
How to&Answers:

Your best bet would be to use proc_open, sleep for your timeout amount and then call proc_terminate if the process still hasn’t completed.

See http://us3.php.net/manual/en/book.exec.php for details on the proc_* family.


Well, I’m not so sure this question would have an answer based on how I asked it, so what I am going to do is do the perl call where php doesn’t wait for a response and have perl write the output to a text file, then have php read this after specified number of seconds, I think this is the simplest way to do this, its just for a small app i am running on a local server