Managing error in PHP and updating report settings

Try - Catch - Finally code blocks to handle error
<?Php
error_reporting(0);// no error reporting 
?>
<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

//  E_WARNING is removed
error_reporting(E_ERROR |  E_PARSE); 

// Reporting E_NOTICE can be good too (to report uninitialized)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
?>
Broadly PHP errors can be classified as
  • parse or syntax errors
  • fatal errors
  • warning errors
  • notice errors
PHP script can be set to display error messages or not by changing display_error setting to On or Off. This setting is available in php.ini file which is a server level setting so not available for shared hosting accounts. But this can be overridden and local settings can be applied to display error or not.

IN our php.ini file there is a setting saying
display_errors = On
With this we can display all types of error and this can be changed to
display_errors=Off
This will not display any error message to visitors.

Local or script level settings

At the script level of any php page we can set the value like this which will change the php.ini setting , here is an example.
<?Php
$one = $two; 
?>
This will give this error message
 Notice: Undefined variable: two in J:\php_files\t\error\test.php on line 13
You may not like this error message to be displayed to your visitors so we can add error_reporting function like this.
<?Php
error_reporting(0);// With this no error reporting will be there
$one = $two; 
?>
No error message will be displayed with the above code.

Development environment

We should display all types of errors in a development environment.
error_reporting(E_ALL);
or
ini_set('display_errors', true);

Production environment

Remember to be cautious when displaying errors on a production server, as it may expose sensitive information to potential attackers. It's generally recommended to enable error reporting during development and testing, and disable it in a production environment. Additionally, it's important to properly handle errors and log them to a secure location instead of displaying them directly to users.

To supress all error message keep these lines at beginning of the page.
ini_set('display_errors', 0);
error_reporting(0);

PHP Error Constants

Value Constant Description
1 E_ERROR (int) Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
2 E_WARNING (int) Run-time warnings (non-fatal errors). Execution of the script is not halted.
4 E_PARSE (int) Compile-time parse errors. Parse errors should only be generated by the parser.
8 E_NOTICE (int) Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
16 E_CORE_ERROR (int) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.
32 E_CORE_WARNING (int) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP.
64 E_COMPILE_ERROR (int) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.
128 E_COMPILE_WARNING (int) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine.
256 E_USER_ERROR (int) User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error().
512 E_USER_WARNING (int) User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error().
1024 E_USER_NOTICE (int) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().
2048 E_STRICT (int) Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
4096 E_RECOVERABLE_ERROR (int) Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.
8192 E_DEPRECATED (int) Run-time notices. Enable this to receive warnings about code that will not work in future versions.
16384 E_USER_DEPRECATED (int) User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().
32767 E_ALL (int) All errors, warnings, and notices.

PHP try-catch-finally Block: Explanation and Examples 🔝

In PHP, the try-catch-finally block is used for handling exceptions. It helps in managing errors in a controlled and structured way.

Key Components

  • try Block: Contains the code that may throw an exception. PHP will monitor this block for any exceptions.
  • catch Block: Executes if an exception is thrown in the try block. It handles the exception and provides an error message or fallback operation.
  • finally Block: (Optional) Always executes after the try and catch blocks, regardless of whether an exception was thrown. It is typically used for cleanup operations, like closing connections or freeing resources.

Example 1: Basic try-catch Block

<?php
try {
    // Code that may cause an exception
    $number = 10;
    if ($number > 5) {
        throw new Exception("The number is too large!");
    }
    echo "This will not be executed.";
} catch (Exception $e) {
    // Code to handle the exception
    echo 'Caught exception: ' . $e->getMessage();
}
?>

Explanation:

  • throw new Exception(): Throws a new exception if the condition is met.
  • catch (Exception $e): Catches the thrown exception and retrieves the error message via $e->getMessage().

Output:

Caught exception: The number is too large!

Example 2: Using try-catch-finally

<?php
$connection = null;
try {
    // Attempt to connect to a database
    $connection = new mysqli("localhost", "user", "password", "database");

    // Throw an exception if the connection fails
    if ($connection->connect_error) {
        throw new Exception("Connection failed: " . $connection->connect_error);
    }

    echo "Connected successfully!";
} catch (Exception $e) {
    // Handle the exception
    echo "Error: " . $e->getMessage();
} finally {
    // This will always execute, even if an exception was thrown
    if ($connection) {
        $connection->close();
        echo " Connection closed.";
    }
}
?>

Explanation:

  • The finally block ensures the database connection is closed, regardless of success or failure.

Output (if connection fails):

Error: Connection failed: Access denied for user 'user'@'localhost'
Connection closed.

Example 3: Multiple catch Blocks

<?php
try {
    // Code that may throw different exceptions
    $num1 = 10;
    $num2 = 0;
    
    if ($num2 == 0) {
        throw new DivisionByZeroError("Cannot divide by zero!");
    }
    
    $result = $num1 / $num2;
} catch (DivisionByZeroError $e) {
    // Handle division by zero error
    echo "Math error: " . $e->getMessage();
} catch (Exception $e) {
    // Handle other general exceptions
    echo "General error: " . $e->getMessage();
}
?>

Explanation:

  • DivisionByZeroError: Specific exception for division by zero errors.
  • Exception: Catches any general exceptions that are not specific.

Output:

Math error: Cannot divide by zero!

Key Points

  • Exception Propagation: If an exception is not caught, it propagates up the call stack. If uncaught, PHP outputs a fatal error.
  • finally Block: Always executes after the try and catch blocks, making it ideal for cleanup operations.
  • Custom Exceptions: You can create custom exceptions by extending PHP's Exception class.

trigger_error(): Generates a user-level error/warning/notice message
Introduction to PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Hire Php Developer

    03-07-2017

    Great tutorial. This tutorial was really helpful to known the error reporting in PHP. Thanks.




    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer