Quickly Add Email Error Reporting to Your PHP Application or Script

I recently needed to add some error reporting onto a custom PHP script I had created. I looked at a few options including using a PHP Mailer include or a complex error logging system when I stumbled across the following built in, PHP function called error_log() which looks like the following, and is so nice and super simple to add in only a single line.

error_log("An error has occurred", 1, "youremail@yourdomain.com");

The code I was working with already provided the user with a friendly looking error via a series of if statements, so it was a simple matter of adding the above single line within the else section and specifying a bunch on unseen variables that would help trouble shoot any issues.

error_log("ERROR : " . date("Y-m-d H:i:s") . " Sent Data: " . $sentdatavarible . " Received Data: " . $receieveddatavarible, 1, "youremail@yourdomain.com");

But what if you don’t want a bunch of emails coming through?

Yes, that’s a good point, not every error is necessarily an issue with the code, it could be due to bad data or credit card details the user has entered. In this case by setting the second option to 3 and defining a file location, you can have all your errors be written to a file on your server instead.

error_log("An error has occurred", 3, 'debug.log');

You can find out more information on the error_log details page on PHP.net.

I hope this helps someone out there 🙂

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *