Skip to content

How to deal with errors in PHP

Every programmer makes errors. We’re humans, after all.

We might forget a semicolon. Or use the wrong variable name. Or pass the wrong argument to a function.

In PHP we have:

The first 2 are minor errors, and they do not stop the program execution. PHP will print a message, and that’s it.

Errors terminate the execution of the program, and will print a message telling you why.

There are many different kinds of errors, like parse errors, runtime fatal errors, startup fatal errors, and more.

They’re all errors.

I said “PHP will print a message”, but.. where?

This depends on your configuration.

In development mode it’s common to log PHP errors directly into the Web page, but also in an error log.

You want to see those errors as early as possible, so you can fix them.

In production on the other hand you don’t want to show them in the Web page, but you still want to know about them.

What you do is, you log them to the error log.

This is all decided in the PHP configuration.

We haven’t talked about this yet, but there’s a file in your server configuration that decides a lot of things about how PHP runs.

It’s called php.ini.

The exact location of this file depends on your setup.

To find out where is yours, the easiest way is to add this to a PHP file and run it in your browser:

<?php
phpinfo();
?>

You will then see the location under “Loaded Configuration File”:

In my case it’s /Applications/MAMP/bin/php/php8.1.0/conf/php.ini.

NOTE: the information generated by phpinfo() contains a lot of other useful information, remember that.

Using MAMP you can open the MAMP application folder and open bin/php, go in your specific PHP version (8.1.0 in my case) then go in conf. In there you’ll find the php.ini file:

Open that file in an editor.

That contains a really long list of settings, with a great inline documentation for each one.

We’re particularly interested in display_errors:

In production you want its value to be Off, as the docs above it say.

The errors will not show up anymore in the website, but you will see them in the php_error.log file in the logs folder of MAMP in this case:

This file will be in a different folder depending on your setup.

You set this location in.. your php.ini:

The error log will contain all the error messages your application generates:

You can add information to the error log by using the error_log() function:

error_log('test');

It’s common to use a logger service for errors, like Monolog.


→ Here's my latest YouTube video

→ Get my PHP Handbook

→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list