-1

I have a PHP script that uses an API. Sometimes the API can be fast, sometimes it’s slow. Is there a way to check if execution time of the get_contents(); is above ex. 2 seconds?

If it goes over this amount i want the included script to stop, and execute the original file.

Ex:

<?php 

    include("file.php"); //if more than 2 sec, continue

    echo "Hello world";

?>
sdfgg45
  • 1,232
  • 4
  • 22
  • 42
  • http://php.net/manual/en/function.set-time-limit.php – Thamilhan Mar 15 '17 at 12:19
  • Your title and your question are asking two different things ("skip" vs. "check"). Please be clearer in what it is you are asking. – ohio818 Mar 15 '17 at 12:22
  • this answer here [Timeout a function in PHP](http://stackoverflow.com/a/10587359/2359679) maybe answer your question. – hassan Mar 15 '17 at 12:30
  • You keep changing the underlying question. The goal of this post is unclear, and the unclearness is evolving. – ohio818 Mar 15 '17 at 12:33

1 Answers1

0

You may use set_time_limit function to set the maximum time limit

.... //some logic
const MAX_EXECUTION_TIME = 2; // for 2 seconds
set_time_limit(self::MAX_EXECUTION_TIME);
file_get_contents(...);
.... // some other logic
Jay Ghosh
  • 674
  • 6
  • 24
  • using `set_time_limit` will throw an error if the execution time is greater than the time you've set ! – hassan Mar 15 '17 at 12:21
  • `Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error.` – hassan Mar 15 '17 at 12:21
  • You're right. Maybe a try catch block would work? Or a better alternative could be to use curl. So something like `curl_setopt($ch, CURLOPT_TIMEOUT, 2)` should do the trick – Jay Ghosh Mar 15 '17 at 12:22
  • 1
    I'm sorry I misinterpreted the OP's question. As far as I know, there is no way of knowing the execution time of a script beforehand as it depends on a lot of variable factors like server speed for eg – Jay Ghosh Mar 15 '17 at 12:24
  • there is another important point, that `set_time_limit` is set the time limit for the whole script, not only part of it. – hassan Mar 15 '17 at 12:28
  • Sorry I had to downvote, but it is fundamentally wrong, since time spent to make an http request is not counted towards script time limit. – Alex Blex Mar 15 '17 at 13:41