PHP display errors at runtime

OK I will admit this post is purely for me to store this little bit of code for times of need. If you have found this post and want to know what it is about then read on.

How to temporarily enable PHP errors without editing your PHP.ini file (so keeping display_errors = Off globally in your .ini file but changing it to “On” just for one script).

Paste the following code into the top of your PHP file:

error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);

If you want to log errors to a particular file you can also add:

ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); // change as required

Job done.

UPDATE – OK job not completely done. I was well aware that using the above settings would not show fatal errors but that never usually bothered me until I hit a problem with someone else’s code on a server with display_errors Off and didn’t know where to start. PHP will not show fatal errors even using the settings above because if it encounters a fatal error the processing stops dead before the error is triggered and thus there is no output as expected – usually this leaves you with a blank page and a silent 500 internal server error, which is highly frustrating!

To set your site to show fatal errors even when your PHP.ini has display_errors as Off then you can add this to your .htaccess file (using Apache):

php_value display_errors 1

That should work as long as your Apache config allows the htaccess file to overwrite all settings.

About the Author

MJ7: aka Mark Jackson @ MJDIGITAL. Digital Consultant - primarily digital marketing, web app design and development, multimedia and SEO techniques. But will happily consult on most IT matters.