PinoyStackOverflower
PinoyStackOverflower

Reputation: 5302

Send email everytime php generates a fatal error

How would I write a PHP code that would send me an email everytime I get a

Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 14373306 bytes) in on line <b>443</b><br />.

I'm running a script wherein a user has this URL and it will be process by my code, but the problem here is that sometimes it results to a Fatal error Allowed memory size exhausted. I want an email to be sent to me that tells me that there has this error at the same time what URL is causing that error.

So the logic is something like this.

if( error == "Fatal Error Allowed memory Size" ) {
 mail("[email protected]", "Fatal Error - URL: http://google.com");
}

I hope the instruction is pretty clear. Your help would be greatly appreciated and rewarded!

Thanks! :-)

Upvotes: 1

Views: 1590

Answers (2)

Vinod Joshi
Vinod Joshi

Reputation: 7862

Init following function inside your php file.

register_shutdown_function('mail_on_error'); //inside your php script

/** If  any file having any kind of fatal error, sln team will be notified when cron will
become fail : following is the name of handler and its type
E_ERROR: 1 | E_WARNING: 2 | E_PARSE: 4 | E_NOTICE: 8
*/

function mail_on_error() {
    global $objSettings;

    $error = error_get_last();
    //print_r($error);    

  if ($error['type'] == 1) {

        // update file path into db
        $objSettings->update_records($id=1,array('fatal_error' => json_encode($error)));

        $exception_in_file_path = __FILE__;
        fatal_error_structure($exception_in_file_path);

  }// end if

}// end mail_on_error

fatal_error_structure should be defined on some global location. like function.inc.php. This will send an email to registered user.


function fatal_error_structure($exception_in_file_path){

        $subject = "FATAL: Cron Daemon has failed";

    sln_send_mail(nl2br("Please check $exception_in_file_path, This cron having FATAL error."), 
        $subject, '[email protected]',$name_reciever='', 'text/plain');

}// end fatal_error_structure

vKj

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71422

You can look at using register_shutdown_function(). It can be used to execute on E_ERROR(fatal error)

register_shutdown_function('shutdown');

function shutdown()
{
  if(!is_null($e = error_get_last()))
  {
    mail("[email protected]", "Fatal Error - ". var_export($e, true));
  }
}

I would however echo thoughts in the comments above that this is best handled using log monitoring.

Upvotes: 4

Related Questions