PHP

PHP Error Handling: Log Problems and Show Safe Messages

INSIGHT • MINDCLAVE

Learn how PHP errors and exceptions differ, how to log problems safely, and how to show useful messages without exposing private details.

Good PHP error handling helps you find bugs without showing visitors private details. The key is to treat development and production differently: during development, make errors easy to see; on a live site, record the details in a protected log and show users a simple message.

This guide explains common PHP errors, shows when to use exceptions, and walks through practical ways to log problems. You will also learn what not to catch and how to avoid hiding a failure behind a message that says everything worked.

What PHP error handling means

PHP can report problems in several ways. A warning or notice may point to a mistake that does not stop the current script. A fatal error can stop the script. An exception is a problem that code can raise and, when handled, respond to in a planned way.

Error handling is the set of choices your program makes when one of these problems occurs. It can decide whether to stop, try a different action, write a log entry, or show a user-friendly response.

These terms are related, but they are not interchangeable. For example, a missing file can cause a warning, while a database library may throw an exception when a query fails. Knowing what kind of problem you are dealing with helps you choose the right response.

Why errors need different treatment in development and production

While building an application, detailed errors can save time. They may show the file and line where a problem occurred. On a live website, that same detail could reveal folder names, database information, or parts of your application.

Set PHP to report errors in both environments, but change where the details go. In development, display them where you can see them. In production, keep them out of the page and send them to a log that only trusted people can access.

Simple rule: Do not turn off error reporting just to make a page look clean. Keep errors available for diagnosis, but control whether PHP displays them to visitors.

PHP settings are often managed in the server configuration or a hosting control panel. The names below are common settings, but the way you change them depends on your server.

  • Development: Set display_errors to On and use error_reporting set to E_ALL.
  • Production: Set display_errors to Off, log_errors to On, and keep error_reporting set to E_ALL.

These settings tell PHP to notice a wide range of problems, while keeping production details out of the visitor’s browser. Test your setup after changing it. Some hosting providers control these settings for you or do not allow every setting to be changed inside an application.

Use logs to keep useful details private

A log is a record of events that can help you understand what happened. PHP can write errors to a server log, or your application can use a logging library. In either case, make sure the log is not available as a public web page.

A useful log entry usually tells you what action failed, when it happened, and enough context to investigate. Avoid putting passwords, access tokens, payment details, or full private user records in logs. Logs can contain sensitive information, so limit who can read them and follow a plan for removing old files.

For a simple application, PHP’s error_log function can record a message:

error_log(‘Could not save the order.’);

That message is better than a silent failure, but it may not be enough to find the cause. You can add safe context, such as an order ID, if that ID is not secret and your site’s privacy rules allow it. Do not use a value from a request as if it were trusted. If you include user input, clean it up and avoid logging large or sensitive values.

For larger applications, a logging library can add levels such as notice, warning, and error. It may also help send entries to a central log service. The important habit is the same: record what a maintainer needs, without exposing private data to visitors or storing more than needed.

Handle expected problems near the code that can fix them

Use a try and catch block when you can take a useful action if an exception occurs. For instance, a payment request may fail, so your application can keep the order marked as unpaid and offer the customer another way to continue.

A catch block should not simply pretend the action worked. If saving a record fails, do not display a success message or continue as if the record exists. Return a clear failure result, show a suitable message, or pass the problem to code that can handle it.

In PHP, a basic try and catch looks like this:

try {

    saveOrder($order);

} catch (RuntimeException $exception) {

    error_log(‘Order save failed.’);

    showSaveError();

}

This example assumes that the code can raise a RuntimeException and that showSaveError gives the user a safe response. In real code, catch the exception types you understand and can respond to. A broad catch can hide a different problem that you did not plan for.

Use finally for cleanup

A finally block runs after the try and catch work, whether or not an exception occurred. It is useful for cleanup, such as closing a resource that your code opened. Do not use it to mark an action as successful, because it runs after both success and failure.

Some resources, such as database connections managed by PDO, are cleaned up when they are no longer needed. Other resources may need explicit cleanup. Follow the rules of the library or resource you use.

Choose exception types that make sense

PHP has built-in exception classes, and libraries can define their own. Catching a specific type helps show which failures your code expects. For example, you might handle an invalid input exception differently from a database connection problem.

Do not use exceptions for every small choice. If a user leaves an optional field blank, that is usually normal input to check with an if statement. Exceptions are more useful when an operation cannot continue as planned or when a deeper part of the application reports a failure.

When you create your own exception, choose a name that describes the problem. Keep the message useful for developers, but do not assume it is safe to show to a visitor. Messages can contain internal details.

How to handle database errors safely

Database failures can happen because of a connection issue, an unavailable server, or a query problem. With PDO, you can configure errors to be reported as exceptions. This lets your code respond in one clear way instead of checking for a failure after every database call.

For example, a PDO connection can be set to use exception mode with the following option:

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Then, handle a database failure where you can choose a safe next step. Do not show the raw database error to the person using the site. It could include table names, query details, or other information that belongs in a protected log.

A simple pattern is to log the event and return a general message:

try {

    $statement = $pdo->prepare(‘SELECT id FROM members WHERE id = :id’);

    $statement->execute([‘id’ => $memberId]);

} catch (PDOException $exception) {

    error_log(‘Member lookup failed.’);

    showGeneralError();

}

This example is only a pattern; the right response depends on the page. A lookup that can be retried may offer another attempt. A failed payment or account update may need a clear status and a support path. Never report that an operation succeeded if the database did not confirm it.

Use a top-level exception handler as a final safety net

Sometimes an exception reaches the end of a request without being caught. A top-level exception handler can log it and show a generic error page. In PHP, you can register one with set_exception_handler.

This should be a final safety net, not a replacement for handling expected failures near the code that can respond to them. The handler receives an uncaught Throwable, which covers PHP exceptions and other throwable errors.

A web application might register a handler like this:

set_exception_handler(function (Throwable $exception): void {

    error_log(‘Uncaught application error: ‘ . get_class($exception));

    http_response_code(500);

    echo ‘Sorry, something went wrong. Please try again later.’;

});

This is a small example, not a complete error page. A real site may need different handling for web requests and command-line tasks. It should also make sure the response has not already started before setting a status code or sending a page.

Notice that the example does not print the exception message or stack trace. Those details belong in a protected log or developer tool, not in a public response.

When a custom PHP error handler helps

PHP also lets you register a custom handler for certain reported errors with set_error_handler. This can help an application log a warning in a consistent way or convert a particular warning into an exception.

Use this feature with care. A custom error handler does not catch every kind of PHP problem. For example, a syntax error may stop the file from running before its handler can be registered. Some fatal problems also need separate attention. Do not assume one custom handler can make every failure safe.

If you convert warnings into exceptions, choose which warning types to convert and test the effect. Turning every notice or warning into an exception may make ordinary issues harder to handle, especially in older code or when working with libraries.

For many sites, correctly set PHP reporting, protected logs, clear try and catch blocks, and a final exception handler are enough. Add a custom error handler only when you have a clear need and understand what it will and will not receive.

Common mistakes to avoid

  • Showing detailed errors in production. File paths and stack traces can reveal how your application is built. Keep them out of public responses.
  • Turning off all reporting. This can hide problems that you need to fix. Log errors instead of ignoring them.
  • Catching everything and doing nothing. An empty catch block can make a failed operation look successful. Log the problem and choose a real next step.
  • Logging secrets. Keep passwords, tokens, and sensitive user details out of logs. Limit log access and retention.
  • Showing exception messages to users. These messages are written for code and may reveal private details. Use a clear, general response instead.
  • Using exceptions for normal input checks. Validate expected input directly. Save exceptions for failures that interrupt the planned work.
  • Assuming a handler fixes the cause. A handler can report a problem, but it cannot make a broken database query or missing file work.

A practical checklist for PHP error handling

Before you put a PHP application online, check the following:

  • PHP reports errors so problems can be found.
  • Detailed errors are not displayed to site visitors in production.
  • Logs are stored somewhere that is not open to the public.
  • Logs do not contain passwords, tokens, or unnecessary personal data.
  • Expected failures have a useful response in the code that can act on them.
  • Uncaught failures create a safe response rather than a blank or misleading success page.
  • You have tested both a normal request and a failure case.

Also decide who checks the logs and how long you keep them. A log that nobody reviews may not help you find a problem. A log kept forever may store more information than you need.

Frequently asked questions

Should I use try and catch around every PHP function?

No. Use try and catch where you can respond to a failure. Wrapping every line can make code harder to follow, especially if the catch block does not take a useful action.

Should I catch Throwable or Exception?

Catch a specific exception type when you know how to handle that problem. A final top-level handler may accept Throwable to catch uncaught exceptions and other throwable errors. Avoid a broad catch in the middle of the application unless you have a clear reason for it.

Can I show the PHP error message to the person using my site?

Usually, no. Show a short message that explains what the person can do next, if anything. Keep technical details in a protected log for the team that maintains the application.

Is error handling the same as input validation?

No. Input validation checks whether submitted data follows your rules, such as whether an email field is filled in. Error handling responds when an operation fails, such as when a database cannot save a valid form. A well-built application needs both.

Build a clear path for every failure

Good PHP error handling does not mean catching every problem and hiding it. It means deciding what should happen when a task fails: give developers enough detail to investigate, keep sensitive information private, and give visitors an honest response.

Start with reliable reporting and protected logs. Handle expected problems where you can take action, and use a top-level handler for anything that slips through. Test the failure paths as carefully as the successful ones, so your application stays clear and trustworthy when something goes wrong.

author-avatar

About M Sultan

Bangash.org is a digital website that provides a variety of online tools and utilities designed to help users with web-based tasks and digital needs.