Current Location: Home> Latest Articles> ini_set and error_reporting use control error output

ini_set and error_reporting use control error output

gitbox 2025-05-28

1. Understand error_reporting and ini_set

  • error_reporting() is a function that sets the error level reported by PHP scripts when running. It can receive an integer parameter representing the type of error that needs to be displayed or hidden.

  • ini_set() is a function used to dynamically modify PHP configuration options, such as display_errors , log_errors , etc.

By combining the two, we can flexibly decide which errors are recorded, which errors are displayed directly, and whether to write the errors to the log file.


2. Basic usage examples

In the following example, we first turn off all error displays and only log errors in the log:

 <?php
// Settings report all errors
error_reporting(E_ALL);

// Turn off error display
ini_set('display_errors', '0');

// Turn on error logging
ini_set('log_errors', '1');

// Set the error log file path(Here&#39;s the demonstration path,Please set the actual project according to your needs)
ini_set('error_log', '/var/log/php_errors.log');
?>

3. Dynamic adjustments according to the development environment

In the development environment, we usually need to see error messages in real time to facilitate debugging; in the production environment, we should turn off the error display and only record the log.

 <?php
if (getenv('APP_ENV') === 'development') {
    // Development Environment
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    ini_set('log_errors', '1');
} else {
    // Production environment
    error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
    ini_set('display_errors', '0');
    ini_set('log_errors', '1');
    ini_set('error_log', '/var/log/php_errors.log');
}
?>

4. Control the displayed error level through ini_set

If you want to display only fatal errors and warnings, you can write this:

 <?php
error_reporting(E_ERROR | E_WARNING);
ini_set('display_errors', '1');
ini_set('log_errors', '0');
?>

5. Things to note

  • ini_set('display_errors', '1') is valid only during script execution, and some server configurations override this setting.

  • It is recommended to turn off display_errors in the production environment to avoid exposure of sensitive information.

  • The log file path needs to have write permissions to ensure that the error log can be correctly recorded.


6. Combined with URL reference examples

If you need to use a URL in your code, this article requires that the domain name be replaced with gitbox.net . For example:

 <?php
$url = 'https://gitbox.net/api/v1/user';
echo "Request an interface address:{$url}";
?>