Covert
Covert

Reputation: 1

Redirect to another page when fatal error occurs

I'm receiving the following fatal error on an application that I'm currently working on.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 1245184 bytes) in C:\xampp\htdocs\myproject\vendor\tecnickcom\tcpdf\tcpdf.php on line 7317

Warning: unlink(./Logo.jpg): No such file or directory in C:\xampp\htdocs\myproject\vendor\tecnickcom\tcpdf\tcpdf.php on line 7801

What I want to do is redirect to another page when a fatal error occurs. The following is the code I'm playing around with but no luck.

set_time_limit(0);
use Spipu\Html2Pdf\Html2Pdf;

try {
    ...
    } catch (Throwable $e) {
        header('Location: http://localhost:8080/docs/generate.php'); exit;
}

The issue over here is that the redirection doesn't happen on fatal error.

Please advise.

Upvotes: 0

Views: 541

Answers (1)

N'Bayramberdiyev
N'Bayramberdiyev

Reputation: 3620

You cannot catch fatal errors in PHP. But there's a workaround that can be useful in your case.

You can register a callback on shutdown using register_shutdown_function.

register_shutdown_function(function() {
    require_once dirname(__FILE__) . '/file.php'; // use ABSOLUTE path
    die();
});

You may wonder redirecting users to another page using header instead of including file.php and stopping the execution of script. Well, you'll get a warning:

Cannot modify header information - headers already sent by...

Since you cannot send any HTTP header in the shutdown callback.

Upvotes: 2

Related Questions