Home > DeveloperSection > Beginner > PHP Error Handling

PHP Error Handling


PHP PHP 
Ratings:
0 Comment(s)
 3251  View(s)
Rate this:

PHP Error Handling

The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error are sent to the browser. Error handling is an important part of a web application development.

In this articles I will described  you, how to handles errors in PHP.

Here I will show you different error handling methods in PHP:

1.       Simple “die()” statement

2.       Custom errors and error trigger

3.       Error Reporting

Now let’s we have a brief idea about these methods, how to use in PHP error handling.

Simple “die( )” Statement:

Below example shows a script that opens a text file:

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>Error Handling </title>

    </head>

    <body>

        <?php

          // open a wrongtext file

        $file = fopen("wrong.txt", "r");

       

        ?>

    </body>

</html>

 

When you debug the above php script then following error will be displayed because the above text file is not found.

Output:

Warning: fopen(wrong.txt) [function.fopen]: failed to open stream: No such file or directory in C:\Apache Server\htdocs\MySiteFile\PHPErroHandling.php on line 14

Now we can handle this error, first of all we test that file is exist or not before access it.

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>Error Handling </title>

    </head>

    <body>

        <?php

         // check file isexist or not

        if(!file_exists("wrongfile.txt"))

        {

            die ("File not found !");

        }

        else

        {

           $file = fopen("wrongfile.txt", "r")     ;

        }

        ?>

    </body>

</html>

 

 

Now debug above code and you will get error like this.

Output:

File not found !

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.

Custom error and errors trigger:

Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context).

Syntax:

error_function(error_level,error_message,error_file,error_line,error_context)

Where, ‘error_level’ is required parameter which specifies the error report level for the user-defined error, must be a value number, ‘error_message ’ is also required parameter which specifies the error message for the user-defined error, ‘error_file’ is an optional parameter which specifies the file name in which error is occurred, ‘error_line’is also optional parameter which specifies the line number in which error is occurred and ‘error_context’ specifies an array containing every variable, and their values, in use when the error occurred.

There is lots of possible errors level such as: E_ERROR, E_WARNING, E_PARSE etc. All errors level is defined by the PHP built function error_reporting($level) function where $level is specifies the above defined error level.  Once you define your custom error handlers you need to set it with PHP built-in function set_error_handler($error_handler, $error_types) where, $error_handler specifies the handler name and $error_types  specifies the type of error.

Now let’s we have an example, creating a function to handle error.

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>Error Handling </title>

    </head>

    <body>

       <?php

            //error handler function

            function customError($errno, $errstr)

             {

                    echo "<b>Error:</b> [$errno] $errstr";

              }

 

            //set error handler

            set_error_handler("customError");

 

             //trigger error

            echo($test);

        ?>

    </body>

</html>

 

Output:

PHP Error Handling

Error Reporting:

The error_reporting() function sets the error_reporting  directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. If the optional level is not set, error_reporting() will just return the current error reporting level. Another error-related setting in PHP is error_reporting. This setting control which types of errors are being logged (or displayed on screen when enabled).

To turn on Error Reportin in PHP, write the following two line of code.

<?php

   ini_set('display_errors', '1');

   error_reporting(E_ALL);

  ?>

And if you just want all Error Reporting off, simply use this:

error_reporting(0);

 

Example: Use E_ALL error level.

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>Error Handling </title>

    </head>

    <body>

       <?php

            ini_set('display_errors', '1');

            error_reporting(E_WARNING);

            $file = fopen("wrongfile.txt", "r");

        ?>

    </body>

</html>

Output:

PHP Error Handling

Example: Use E_ERROR error level

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title>Error Handling </title>

    </head>

    <body>

       <?php

            ini_set('display_errors', '1');

            error_reporting(E_ERROR);

            $file = fopen("wrongfile.txt", "r");

        ?>

    </body>

</html>

Debug the above code, No error message will be displayed because error reporting provide only warning message.


Don't want to miss updates? Please click the below button!

Follow MindStick