How to Display All PHP Errors: A Complete Guide

How to Enable and Display All PHP Errors: From Debugging to Production

Final: php show all errors

As a PHP developer, you know the frustration of troubleshooting an issue in your code. One of the most challenging aspects of it is identifying the root cause of the problem. Without clear error messages, you may spend hours trying to identify the issue, only to discover it was a simple syntax error.

By default, PHP does not display errors to the user or log them to a file.

So enabling error reporting in PHP allows you to see any errors in your code, such as syntax errors or undefined variables.

Let’s show you how to enable and display all PHP errors. But first…

A PHP hosting provider is vital for specialized support and optimized environments tailored for PHP-based applications. Discover the top PHP hosting providers by visiting our curated list at HostAdvice’s PHP Hosting providers page.

Top PHP Hosting Providers We Recommend

ProviderUser RatingBest For 
4.8cPanel PHPVisit FastComet
 4.6Managed PHPVisit Hostinger
 4.0User-FriendlinessVisit IONOS

Takeaways
  • Displaying all errors in PHP is crucial for effective debugging, code quality, and application reliability
  • Different methods to display errors in PHP include modifying the php.ini file, using .htaccess files, and applying runtime configurations with ini_set() and error_reporting()
  • Custom error handling can be achieved with set_error_handler(), providing personalized error messages, advanced logging strategies, and specific error-handling behavior
  • By setting error_reporting to E_ALL, you can capture every error and warning, enhancing debugging and improving code quality
  • Utilizing .htaccess files or runtime configurations enables granular control over error display settings, offering flexibility and adaptability in error management
  • Display errors on-screen during development for quick issue identification, but log errors to a file or logging system in production to maintain security and a clean user experience
  • Understanding PHP’s configuration file behavior across different environments, such as server modules and CGI/CLI versions, allows for better optimization and adaptability in your development process

Types of Errors in PHP

Writing code is often the easy part of software development, but going through errors can be a real headache.

A survey found that developers spend 49.9% of their programming time debugging and validating software.

So what are errors? In PHP, errors occur when the script encounters a problem or an unexpected condition that prevents it from running correctly. These errors can be caused by a variety of factors, including syntax errors, logical errors, and runtime errors.

Let’s look at different types of errors to know why errors occur.

1. Syntax Errors

Syntax errors occur when you write the code incorrectly and violate the rules of the PHP language. These errors prevent the code from executing and are the most common type of errors in PHP.

Here are some of the characteristics of syntax errors in PHP:

  • Syntax errors are detected by the PHP interpreter during the compilation process. The interpreter generates an error message indicating the problem.
  • These errors occur due to incorrect spelling, missing or misplaced punctuation, or incorrect use of PHP language constructs.
  • Syntax errors prevent the code from executing or cause the code to produce unexpected results.

Let’s look at some examples:

Missing Semicolon

<?php
echo "Hello, World!"
?>

This code produces a syntax error because the semicolon is missing after the echo statement. The correct code should be:

<?php
echo "Hello, World!";
?>

Incorrect Variable Name

<?php
$my_variable = "Hello, World!";
echo $my_varable;
?>

The code above produces a syntax error. The variable name is misspelled in the second line. The correct code should be:

<?php
$my_variable = "Hello, World!";
echo $my_variable;
?>

By understanding syntax errors and their characteristics, you can quickly identify and fix them.

2. Runtime Errors

Runtime errors occur during the execution of the code. They are caused by a variety of factors, such as:

  • Improper file permissions
  • A lack of system resources
  • Invalid function arguments

Runtime errors are difficult to diagnose and fix, as they often require in-depth knowledge of the system environment and the code being executed.

Examples of runtime errors:

Out of Memory Error

<?php
$big_array = array();
for ($i = 0; $i < 1000000; $i++) {
   $big_array[] = $i;
}
?>

This code produces a runtime error because it tries to allocate too much memory for the $big_array variable. The correct way to handle large arrays in PHP is to use generators or streams to avoid running out of memory.

Invalid Function Arguments

<?php
function divide($numerator, $denominator) {
   return $numerator / $denominator;
}

echo divide(10, 0);
?>

You will get a runtime error because the code above tries to divide a number by zero, which is an invalid operation. To handle this error, check the denominator for zero before calling the divide function.

3. Logical Errors

eTutorialsPoint defines logical errors as “a type of error that occurs when perfectly valid code does exactly what it is instructed to do, but that was not what the writer intended.”

Simply, code is syntactically correct but produces unexpected or incorrect results due to errors in the logic of the code.

For example:

Incorrect Program Flow

<?php
for ($i = 1; $i <= 10; $i++) {
   if ($i % 2 == 0) {
       continue;
   }
   echo $i . "<br>";
}
?>

This code produces a logical error because it skips even numbers using the continue statement, but the loop should print only odd numbers. The correct code should be:

<?php
for ($i = 1; $i <= 10; $i++) {
   if ($i % 2 != 0) {
       echo $i . "<br>";
   }
}
?>

4. Fatal Errors

Think of fatal errors as “game over” errors. When a fatal error occurs in PHP, it’s like hitting a brick wall that stops the game from continuing. The code cannot proceed past the error, and the script must be fixed before running again.

There are three types of fatal errors:

  • Runtime fatal error
  • Startup fatal error
  • Compile time fatal error

Here’s an example of a fatal error in PHP:

<?php
class MyClass {
   public function myMethod() {
       return $this->myProperty;
   }
}

$obj = new MyClass();
$obj->myMethod();
?>

The myProperty property is not defined in the MyClass class. The correct code should be:

<?php
class MyClass {
   public $myProperty;
   public function myMethod() {
       return $this->myProperty;
   }
}

$obj = new MyClass();
$obj->myProperty = "Hello, World!";
echo $obj->myMethod();
?>

5. Warnings

PHP warnings are messages the PHP interpreter generates when it encounters a problem in the code. They, however, don’t prevent the code from executing.

Warnings are less severe than fatal errors and can be used to identify potential issues in the code.

<?php
echo $my_variable;
?>

This code will produce a warning because the $my_variable variable is not defined. To correct it, define the variable.

<?php
$my_variable = "Hello, World!";
echo $my_variable;
?>

Enabling Error Reporting in PHP

Enabling error reporting helps you to pinpoint issues quickly and fix them. This saves you time and improves the overall quality of your code.

You can enable or disable error reporting using several approaches, including modifying the php.ini file, using the ini_set() function, or the error_reporting() function.

Let’s take a closer look at the steps involved in enabling error reporting in PHP using these approaches:

Approach 1: Editing the php.ini File

The php.ini file is a configuration file used by PHP to specify various settings, including error reporting. To enable error reporting using this approach, follow these steps:

  1. Locate the php.ini file in your PHP installation directory
  2. Open the file in a text editor
  3. Locate the line that reads display_errors = Off and change it to display_errors = On
  4. Save the changes and restart your web server to apply the new settings

Now, your PHP scripts will display errors on the screen, allowing you to identify and fix issues more efficiently.

Approach 2: Using the ini_set() Function

This function allows you to modify the value of the display_errors parameter at runtime. Here is how to enable error reporting using this approach:

  1. Add the following code at the top of your PHP script
ini_set('display_errors', 1);
error_reporting(E_ALL);
  1. Save the changes and reload your web page

To disable error reporting using the ini_set() function, set the value of the display_errors parameter to 0.

ini_set('display_errors', 0);
Note
NOTE: This code should be added to the top of your PHP script. It should run before any other code is executed.

By setting the display_errors parameter to 0, you’re telling PHP not to display any error messages to end users. This is useful in production environments where you don’t want users to see error messages.

Approach 3: Using the error_reporting() Function

This function allows you to specify which PHP errors are reported at runtime. It’s also used to set different error reporting levels based on your script’s duration.

The error_reporting() function accepts one argument: a bitmask or an integer representing the error level.

Add the following code at the top of your PHP script:

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

The first line sets the error reporting level to E_ALL. This means that all errors, warnings, and notices will be reported. The second line enables the display of error messages to end-users.

Remember to save the changes and reload your web page.

The error_reporting() function accepts several error levels, which are predefined constants in PHP. Some of the common error levels include:

  • E_ERROR – fatal runtime errors that cause the script to halt.
  • E_WARNING – non-fatal runtime errors that don’t cause the script to halt.
  • E_NOTICE – non-fatal errors that indicate potential issues in your code.
  • E_ALL – includes all errors, warnings, and notices.
  • E_COMPILE_ERROR – Fatal errors that occur during compilation, such as a missing or corrupted file. This error level indicates an issue with the PHP installation or file system and requires immediate attention.
  • E_PARSE – Compile-time errors generated by the PHP parser. It indicates an issue with the syntax of the code and usually requires changes to the code itself.

You can also use the bitwise operators to combine different error levels. For example, to report all errors except notices, you can use the following code:

error_reporting(E_ALL & ~E_NOTICE);

This code sets the error level to E_ALL and then uses the bitwise NOT operator (~) to exclude the E_NOTICE level.

Tip
Expert Tip: The approach you choose depends on your specific use case and development environment. For example, editing the php.ini file is a good approach if you want to enable error reporting globally across all your PHP scripts.

Also, note that you should use error reporting judiciously. While it’s essential for debugging and troubleshooting, displaying error messages to end users also presents a security risk. It can reveal sensitive information about your application or server.

Importance of Error Reporting in PHP

Imagine writing a complex application plagued by errors, but you have no idea where the errors are occurring, or worse, they are not even being reported. That’s the stuff of developer nightmares.

That’s why error reporting in PHP is crucial. Here’s why:

  1. Debugging – When errors occur in your PHP code, error reporting provides detailed information about what went wrong.
  2. Efficiency – By reporting errors, you can identify and fix issues more efficiently. This saves time and resources in the long run.
  3. Security – For example, if an error message displays sensitive information, an attacker can use that information to exploit your application.
  4. Continuous improvement - You always want feedback that can help you improve your code over time. By identifying common errors, you can improve your coding practices and reduce the number of errors in your code.

Displaying Errors

Whether you’re a seasoned developer or just starting, displaying errors is an essential tool in your debugging arsenal.

Why Displaying All Errors in PHP Is Crucial

As developers, we strive to create reliable and high-quality PHP applications. So, for several reasons, you want to know all errors during the development phase for:

1. Easier debugging

You can spot issues in the code, such as syntax errors, undefined variables, or incorrect function usage.

2. Improved security

Displaying all errors during development helps you uncover security vulnerabilities, such as SQL injection or cross-site scripting (XSS) risks.

Addressing these issues early on prevents potential data breaches or unauthorized access to your application.

Example:

Suppose you have an SQL query that uses unsanitized user input:

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

Errors will reveal if this code is susceptible to SQL injection. This will prompt you to fix the issue using prepared statements or other security best practices.

3. Performance Optimization

Displaying all errors highlights performance bottlenecks, such as inefficient loops, memory leaks, or excessive database queries.

When you identify these issues, you can optimize the code and ensure better performance for the end users.

For instance, if a PHP script consumes a large amount of memory, displaying errors will expose this issue.

4. Better Code Maintainability

Consider a scenario where an error message highlights the use of a deprecated PHP function.

Displaying this error prompts you to replace the deprecated function with a more modern and efficient alternative, thus improving code maintainability.

FastComet
FastComet was established back in 2013. Due to its variety of hosting options, flexible price points, and reliable customer service, it’s one of the most popular providers available in the US and around the world. Alongside its free site migrations, built-in firewall, and free daily/weekly backups, FastComet guarantees 99.9% uptime.
Visit FastComet

Different Ways to Display Errors

There are several methods available to display errors in PHP. Each method has its advantages and disadvantages, depending on the development environment and specific use cases.

1. php.ini Configuration File

You can enable or disable error reporting globally by modifying the php.ini configuration file.

PHP’s configuration file is a file that is read during startup, with varying behavior depending on the environment.

In server module versions, such as Apache with mod_php, the php.ini file is read once when the web server starts. This means that any changes made to the php.ini file require a server restart to take effect.

Advantages

  • Global error reporting settings apply to all PHP scripts running on the server, ensuring consistent behavior.
  • No need to modify individual PHP scripts.

Disadvantages

  • Requires access to the server’s php.ini file, which may not be possible in shared hosting environments.
  • Changes in the php.ini file affect all applications on the server, which might not be desirable.

2. Runtime Configuration Using ini_set() and error_reporting() Functions

Using the ini_set() and error_reporting() functions, you can control error reporting in individual PHP scripts.

Advantages

  • Provides granular control over error reporting settings for each PHP script.
  • Does not require access to the server’s php.ini file.

Disadvantages

  • Changes must be made in each PHP script. This can be time-consuming for large projects.

3. .htaccess Configuration

In PHP, utilizing .htaccess files offers a flexible and non-intrusive method to manage error reporting settings on a per-directory basis.

Apache .htaccess files provide an alternative to modifying the main configuration file. This allows you to configure specific directories of the web server without affecting the global settings.

It’s particularly useful in shared hosting environments, where you might not have access to the main server configuration file.

To enable error reporting using an .htaccess file, create or edit the .htaccess file in the desired directory, and add the following lines:

php_flag display_errors On
php_flag display_startup_errors On
php_value error_reporting E_ALL

Advantages

  • Allows you to control error reporting settings for a specific directory and its subdirectories.
  • Doesn’t require access to the server’s php.ini file.

Disadvantages

  • Only applicable in Apache-based hosting environments.
  • Not as flexible as using ini_set() and error_reporting() functions in individual scripts.

4. Custom Error Handler

This often underutilized feature opens the door to unparalleled customization in error handling. It enables you to create a tailored debugging experience that caters to your project’s unique requirements.

By implementing a custom error handler with set_error_handler, you can:

  • Personalize error messages and formats
  • Implement advanced logging strategies
  • Define specific error-handling behavior

To get started with a custom error handler, define a function that takes the necessary parameters, such as error type, message, file, and line number, and then call set_error_handler with your custom function:


function custom_error_handler($errno, $errstr, $errfile, $errline) {
   // Your custom error handling logic here
}

set_error_handler("custom_error_handler");

Advantages

  • Provides complete control over error handling, including customizing error messages, formatting, and logging.
  • Allows handling specific error types, filtering out less important errors.

Disadvantages

  • Requires more effort to set up and maintain compared to other methods.

Read more about FastComet

Expert and User Insights by FastComet Customers
Top-rated
4.8
Based on 1591 user reviews
  • User Friendly
    4.9
  • Support
    4.9
  • Features
    4.8
  • Reliability
    4.9
  • Pricing
    4.7
Visit Site

Code Snippets for Displaying Errors in PHP Using Various Methods

1. Setting the error_reporting Directive to E_ALL

To display all errors in PHP using the error_reporting directive, you set the value to E_ALL. This displays all types of errors and warnings.

This method is relatively simple. Add this single line of code to your PHP script to display errors.

error_reporting(E_ALL);

This line of code tells PHP to report all errors and warnings—syntax, runtime, and logical errors.

This method is especially useful in the early stages of development when you’re still ironing out the kinks in your code.

2. Using the ini_set() Function to Set error_reporting

This function allows you to modify the value of the error_reporting parameter at runtime. This means you can change the parameter’s value based on your needs.

ini_set('error_reporting', E_ALL);

You can change the error_reporting value dynamically, such as when testing specific parts of your code.

3. Setting the display_errors Directive to On

Change the value of the display_errors parameter in the php.ini file.

display_errors = On

Setting the display_errors directive to On approach is perfect in the early stages of development when you’re still debugging and troubleshooting your code.

4. Using the error_log() Function to Log Errors

This function allows you to send an error message to the server error log, a file, or even a remote destination.

Using the message_type parameter, you can control where the error message is sent, whether to a file, email, or PHP debugging connection.

One benefit of using the error_log() function is that it provides a lot of flexibility regarding where and how you display error messages.

For instance, you can send error messages to a specific file, making it easy to review and troubleshoot issues in your code. Additionally, you can customize the formatting of the error message and even include extra headers if needed.

error_log('An error occurred', 0);

See this article to learn more about the message_type that directs where the error will go.

Tip
Expert Tip: error_log() function should be used in conjunction with other error reporting methods, such as setting the display_errors directive to On or using the error_reporting() function.

Error Reporting in PHP

1. Best Practices for Error Reporting in PHP

You must balance identifying and fixing issues efficiently while not revealing sensitive information to end users.

In production environments, we recommend you turn off error reporting to avoid exposing sensitive information, such as database credentials or file paths, to end-users.

To turn off error reporting in a production environment:

  • Set the display_errors directive to Off in the php.ini file
  • Use the ini_set() function to set it to Off at runtime

Note that the error messages will not be displayed to end users but will still be logged for later review.

Why Is It Important to Log Errors?

By logging errors to a file, you keep track of issues that occur in your code.

To log errors to a file, use PHP’s error_log() function. This allows you to send error messages to a specific file or location.

Remember, as a developer, you should make it a habit to regularly review error logs. This way, you can identify and fix potential issues in your code before they become major problems. Here are some tips to help you:

  • Group errors by type and severity to prioritize fixes
  • Identify patterns in errors to uncover underlying issues
  • Use tools such as debuggers and profilers to pinpoint the source of errors
  • Regularly test your code to catch potential issues before they occur in production environments

2. Code Snippets for Implementing Effective Error Handling in Your Applications

Let’s look at the code snippets for implementing the best practices for error reporting in PHP.

  • Turning Off Error Reporting in Production Environments

As we said earlier, to turn off error reporting in a production environment, set the display_errors directive to Off in the php.ini file, or use the ini_set() function to set it to Off at runtime.

Here is how to use the ini_set() function to turn off error reporting:

<?php
  ini_set('display_errors', 0);
  ini_set('log_errors', 1);
  ini_set('error_log', '/path/to/error.log');
?>

The 0 value in ini_set(‘display_errors’, 0) means errors will not be displayed on the screen.

The 1 value in ini_set(‘log_errors’, 1) means errors will be logged to a file.

The ‘/path/to/error.log’ in ini_set(‘error_log’, ‘/path/to/error.log’) specifies the file path where the errors will be logged.

  • Logging Errors to a File

To log errors to a file, use PHP’s error_log() function.

<?php
  ini_set('log_errors', 1);
  ini_set('error_log', '/path/to/error.log');
  error_log('An error occurred');
?>

In the code above, we’re using the error_log() function to log the error message ‘An error occurred’ to a file. We’re also using the ini_set() function to specify the location of the error log file.

Note
NOTE: Use a unique file name for each error log, and set appropriate permissions to ensure that only authorized users can access the error log file.
  • Reviewing Error Logs Regularly

To review error logs regularly, use a text editor or log viewer to read the error log file. Here’s an example of how to read an error log file using the command line:

$ tail -f /path/to/error.log

The tail command displays the last 10 lines of the error log file, and the -f option follows the file as new errors are logged.

Expert Tip

To enhance error reporting in PHP:

  • Use descriptive error messages
  • Add error handling to your code
  • Test your code thoroughly to catch potential issues before they occur in production environments

Solving PHP Errors Like a Pro

In software development, debugging and troubleshooting is an inevitable part of the process. And errors can be frustrating and time-consuming to track down.

Enabling error reporting, setting appropriate error reporting levels, logging errors to a file, and regularly reviewing error logs are all critical components of effective error reporting in PHP.

Implementing these best practices allows you to streamline your debugging process, minimize downtime, and keep your applications running smoothly.

Hostinger
Boost your website's performance with Hostinger's ultra-fast hosting solutions at unbeatable price. Offering everything from Shared, Managed WordPress, Managed WooCommerce, Cloud, VPS to Game Server Hosting, Hostinger ensures maximum uptime and premium security.
Visit Hostinger

Next Steps: What Now?

  • Review your current PHP error reporting settings and make sure they are enabled. Set the appropriate level for your development or production environment.
  • Test your PHP code thoroughly to ensure all errors are properly reported and logged.
  • Set up a logging system to capture and store all PHP errors that occur.
  • Regularly review your error logs to identify and fix any issues with your code. Use the information in the logs to debug and improve your code.
  • Consider using third-party error reporting tools and services, like Sentry or Bugsnag, to enhance your error reporting and analysis capabilities.
  • Keep your PHP installation and any third-party libraries updated to ensure you use the latest and most secure code.
  • Check out our comparison of GET PHP HOST vs. Kamatera to find the best option for your needs.
  • Find the Best PHP Hosting Providers

Further Reading – Useful Resources

Frequently Asked Questions

How can I display all errors in PHP?

One option to display all errors in PHP is to modify the php.ini file, which sets the global error reporting settings. Change the display_errors and error_reporting directives to display all errors (E_ALL) throughout your application.

Another approach is to use an .htaccess file for Apache-based environments or set runtime configurations within individual PHP scripts.

Should I display errors on the screen or log them to a file?

During development, displaying errors on the screen helps you to quickly identify and fix issues. However, in production, avoid showing errors on the screen to prevent exposing sensitive information, confusing users, or inviting potential attacks. Log errors to a file instead.

How do I log errors to a file in PHP?

Set the log_errors directive to On in the php.ini file, or use the ini_set() function and set it to On at runtime. You can also specify the path and name of the log file using the error_log directive in the php.ini file or by using the ini_set() function to set it at runtime. For example, ini_set(‘error_log’, ‘/path/to/error.log’).

How can I review error logs in PHP?

You can access the error log file directly using a file manager or via an FTP client. The error log file is usually named error.log and is located in the server’s root directory or in the logs directory. You can also view error logs using a command line interface (CLI) or through your web hosting control panel.

10 Best VPS Hosting on Reddit: Most Recommended Providers 2024

Reddit is a popular source for hosting recommendations, including VPS hosting. With multiple conversations on choosing a service and dozens o...
4 min read
Ela Gal-Kfir
Ela Gal-Kfir
Digital Marketing Specialist

HostAdvice Speaks to ScalaHosting: An Interview with Chris Rusev

HostAdvice had the opportunity to speak with Chris Rusev, the CEO and co-founder of , a web hosting company that offers shared, cloud VPS, and res...
8 min read
Eddie Segal
Eddie Segal
Digital Marketing Specialist

Email Deliverability: What Is It, Key Factors & Best Practices

What is Email Deliverability? Think of it like mailing a letter and making sure it lands right in the recipient's hands, not lost or thrown...
17 min read
Ela Gal-Kfir
Ela Gal-Kfir
Digital Marketing Specialist

Email Marketing vs. Social Media: Which is More Effective?

What is Email Marketing? Email marketing is a  that involves companies reaching out to potential and existing customers via email ...
10 min read
Ela Gal-Kfir
Ela Gal-Kfir
Digital Marketing Specialist
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.
Click to go to the top of the page
Go To Top