PHP

How to "catch" max execution time error in php

Daniel Verner -

Introduction
Have you been in the situation where you wanted to "catch" the max execution timeout, or other fatal errors in PHP? Ever wondered about if this is possible? The short answer is you cannot "catch" it, because it is not an exception. It is a fatal error. So, this could be the end of the article. 
But fortunately there is another way of doing it. In PHP there are so called shutdown functions which are executed when the script finishes. They are called when the script finishes regularly, and also when an error occurs. 
Let's create a class which will handle the max execution time for us. Once it is handled you can do some logging, send out notifications, etc.

TL;DR;
use Illuminate\Support\Str;

class Shutter {
  
  public function shutdown()
  {
    if ($this->hasTimeoutOccurred()) {
      dump('timeout');
    }
  }
  
  private function hasTimeoutOccurred(): bool
  {
    $lastError = error_get_last();
    
    if (!$lastError) {
      return false;
    }
    
    if (Str::startsWith($lastError['message'], 'Maximum execution time')){
      return true;
    }
    
    return false;
  }
}

ini_set('max_execution_time', 1);
$shutter = new Shutter();
register_shutdown_function(fn() => $shutter->shutdown());

while(1);




How it works
We've created a simple class, which has a public function which will handle the shutdown event for us:
public function shutdown()
As I mentioned earlier the registered shutdown functions are also executed when the script ends normally. So we need to check if the max execution timeout error has happened:
if ($this->hasTimeoutOccurred()) {
We can do it by getting the last error using the error_get_last(); function and check if the message is the one we want to handle:
if (Str::startsWith($lastError['message'], 'Maximum execution time')){
   return true;
}
The rest of the code is just a piece for testing. Set the timeout to 1 second, who has the time to wait for 30 seconds when testing... :-). 
Create an instance of the class, and register the shutdown function:
$shutter = new Shutter();
register_shutdown_function(fn() => $shutter->shutdown());
I'd like to note that in this example I am using the PHP 7.4 short closure (aka arrow function) as a callback. 
I have at least two reasons to do so:
  1. I don't like to pass in the callable as string, it is error prone, the IDE doesn't recognize it as a function, and it is ugly.
  2. The arrow function doesn't have it's own scope, so it inherits the parent's scope, therefore I can access the instantiated variable without the use($shutter). 

If you'd like to learn more about how the shutdown functions work check the official documentation here.

Tags: PHP · maximum execution time · error handling

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • Happy birthday 🎁🎈🎂 Filip - #

  • Another day another #mandarinacakeshop 🎂 😀 - #

  • Happy Birthday Ognjen! And marry Christmas to all other 🎄#notacakeshop - #

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan 🥂 - #

  • #happybirthday Lidija 🍾 - #

  • Say hi 👋 to our newest team member ☕️ - #

  • #bithday #cake 😻 - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday 🎂 Miloš - #

  • Happy Birthday 🎂Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday 🎂 Ognjen - #

  • Wish you all a merry Christmas 🎄🎁 - #

See more!

© 2024 42coders All rights reserved.