How to show errors and handling errors in php

Now a days, PHP is the most popular server-side web programming language, so it’s important to know how to resolve any errors that may occur when PHP code is executed.

Here, we will look at the basics of how to do error handling in PHP, using the built-in functions, writing custom error handler functions, and with Exception error handling

 

Types of Errors in PHP

There are two fundamental types of errors in software:

  1. Internal Errors: These are the logic errors in our code. These errors can be prevented to a very large degree by careful programming.
  2. External Errors: These are errors related to the interactions with the world outside of our code (e.g., failing to opening a file or database, the network connection dropping, being unable to load a certain PHP module, etc.). These errors will always occur, but their impact can be mitigated. The better we prepare our code for these external errors, by assuming as little as possible when code is executing, the less these errors will negatively affect our program.

 

Deals with PHP Errors

Once errors occur and we detect them, there are four fundamental ways to deal with them:

  • Display the Error: This allows the error to be shown to the developer and/or user when the program is being executed.
  • Log the Error: This allow the errors to be stored and reviewed from a textual log file.
  • Act on the Error: The type of action needed will be different for each program situation.
  • Ignore the Error: This should always be avoided.

Here, we will focus on the displaying, logging, and handling of errors. Once we know how to handle errors, then we can act on them easily.

 

Showing Errors and Error Reporting Settings

Depending on if we are running code in production or in development, we might want to turn on or off reporting certain types of errors.

There are different locations where we can control what error types are to be reported:

  • In the php.ini file
  • In the .htaccess file on web server
  • From our own PHP code

 

Display PHP Errors

There are four possible options for showing PHP errors:

  • error_reporting: Set the error reporting level. The default value is: “E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED,” meaning this setting does not show E_NOTICE, E_STRICT and E_DEPRECATED level errors.
  • display_errors: Set it to “ON” (default is “OFF”) if errors are to be printed to the screen.
  • log_errors: This indicates whether or not error logging should be done; default value is “on.”
  • error_log string: Sets the name of the file where script errors should be logged.

 

Let’s see how we can use these configuration options.

During development, we might want to turn all error reporting from the php.ini:

display_errors = on                                                                                                           error_reporting = E_ALL

We could do the same from our PHP code during runtime by calling the error_reporting() function:

To turn on error logging and log the errors to our own specific log file (instead of the default error log file, which is often the web server error log file or the syslog file), we could configure PHP with:

log_errors = on                                                                                                                 error_log = "/tmp/php-error.log"

Now log errors via PHP code:

error_log( "This code has errors!" );

 

Custom error handling

Now that we can configure PHP to tell it what types of errors to report on, we need to be able to handle different error types in our own way. Just displaying standard PHP error messages is often not good enough.

We want to handle the error and display our own messages when an error happens. For this, we can use the set_error_handler() function.

Here is a very simple custom error handling function:

// error handler function                                                                                     function errorHandler($errno, $errstr) {                                                                                                 echo "Error: [$errno] $errstr";                                                                                                                     }                                                                                                                                                  // set error handler                                                                                                       set_error_handler("errorHandler");                                                                                                                 // trigger an error                                                                                                                           echo($foo); // undefined variable!

So when an error occurs, the custom error handler function is called with an error-number argument and an error-string argument. These two arguments are passed from the set_error_handler() call to our function.

There are more arguments we could use, as we will soon see, but the output of running this code would be.

Error: [8] Undefined variable: foo

Let’s see what a slightly less simple custom error handling function could look like. This error handler should be able to detect the error types and decide what action to take and/or what error message to show.

function errorHandler($errno, $errstr, $errfile, $errline) {                                                                         switch ($errno) {                                                                                                                          case E_NOTICE:                                                                                                                      case E_USER_NOTICE:                                                                                                                        case E_DEPRECATED:                                                                                                              case E_USER_DEPRECATED:                                                                                                                  case E_STRICT:                                                                                                                            echo("STRICT error $errstr at $errfile:$errline n");       break;                                                                        case E_WARNING:                                                                                                                    case E_USER_WARNING:                                                                                                                      echo("WARNING error $errstr at $errfile:$errline n");       break;                                                                        case E_ERROR:                                                                                                                        case E_USER_ERROR:                                                                                                            case E_RECOVERABLE_ERROR:                                                                                                                    exit("FATAL error $errstr at $errfile:$errline n");                                                                                            default:     exit("Unknown error at $errfile:$errline n");                                                                                          }                                                                                                                                                   }                                                                                                                      set_error_handler("errorHandler");                                                                                                      $foo = false;                                                                                                                            if (! $foo) {                                                                                                                          trigger_error('Value $foo must be true', E_USER_NOTICE);                                                                                            }

Note how we are grouping the handling of certain error types using the fall-through functionality of the switch-case statements.

The output would be something like:

STRICT error Value$foo must true at /tmp/test.php:32

 

Now we can handle types of errors differently (or the same) and show custom error message, too. Of course, a real custom error handling function should be able to do much more with errors and possibly act upon them in a specific and sensible way.

 

It is important to keep custom error handling function simple and robust to ensure no errors occur within this function itself, as those would not get reported. There are several PHP libraries that can help us for creating more advanced error handling.



Was this article helpful?

Top Related Jobs

Top Freelance jobs are waiting for you, View & apply to earn more.

  • 2 Laravel Developer needed

    $18, Hourly | Italy
    Must have 3+ years of Laravel experienceFull Time for 3-5 monthsAgencies Please do not applyDelhi NCR PreferredMay need to work in office located in D...
  • CSS editor

    $18, Hourly | Singapore
    My website isnt working as I would like and I have been told its because i have some missing css code or need to write some css code.The issues are:1...
  • Need an expert PHP developer to update an existing PHP code

    $24, Hourly | Ireland
    Need an expert PHP developer to update an existing PHP codeI have an existing PHP code and needs some updates / changes to itThis will need quick unde...
  • Backend Analytics Dashboard

    $18, Hourly | United States
    Searching for developer to clean up analytics dashboard from the backend of my iOS app. This information is currently shown for me on my website via l...
  • ffmpeg maintenance

    $18, Hourly | United States
    Small job, need to have a feature fixed on ffmpeg that is creating a error message
  • Laravel/PHP Engineer

    $14, Hourly | Ukraine
    The Laravel/PHP Engineer is responsible for contributing to the design and implementation of full stack Laravel PHP applications. You will be the deve...
  • PHP/JAVA developer needed for online experiment

    $18, Hourly | United States
    the project is about using PHP/JAVA to develop web pages for an online experiment. It requires proficient skill on PHP/JAVA.
  • Web development for our Social Media project (Angular4 Javascript, PHP, Symfony)

    $24, Hourly | Singapore
    This is an existing Social Media website which we need to be improved. We have a list of features which we want to add and we are ready to provide it...


People also searched for

Natural Language Processing in Python
Natural Language Processing in Python
Web Development

NLP is a branch of data science that consists of systematic processes for analyzing, understanding, and deriving information from the text information in a smart and efficient mann...

Read More
How to post a Job & Hire a great WordPress developer
How to post a Job & Hire a great WordPress develop...
Web Development

WordPress is an open source Content Management System (CMS), which allows the users to build dynamic websites and blog. WordPress is the most popular blogging system on the web and...

Read More
Some Useful JavaScript Tips,Tricks and Best Practices
Some Useful JavaScript Tips,Tricks and Best Practi...
Web Development

As you know, JavaScript is the top programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJ...

Read More

You are freelancing Ninja?

Try Toogit Instant Connect today, The new virtual assistant for your freelancing world.


What are the benefits to hire a php developer on Toogit?

Hire PHP developer on Toogit to build a website as per the requirement of your business in a convenient manner. A team of professionals can undertake the requirement of your business and can turn your ideas into reality. Hiring PHP developer is a must for you if you want to build a PHP based site with a professional look. Web developers from all over the world are opting for this software to build a site because of its cost effectiveness, flexibility, simplicity and free availability. Hire PHP developers on Toogit to accomplish your business projects.

  • Flexible option: Our multiple models are designed to give you the flexibility in hiring your team at your own budget and project requirements.
  • Build your own team: Choose from a variety of technologies and create your dream team or your own IT team.
  • Transparency at all levels: Options to choose from a pool of talented resources, interviewing them as per your own standards and hiring the right resource.
  • Complete control: Assign tasks at your own will or give the control to the team to lead the development.

What are php developers?

PHP developers develop programs, applications, and web sites using the dynamic scripting language PHP. PHP is known for web development and business applications. Depending on job function, PHP developers could also be classified as software developers or web developers. Because the language is so ubiquitous in web site development and business, PHP can be a good choice for freelance or contract developers.

Mistakes while hiring the PHP Developers

Common mistake that need to be avoided while hiring a PHP developer

  1. Not examining the previous work effectively: Basically, you have to judge the work of the PHP Developer when you are trying to hire them. Of course, you'll have some idea of the skills that are required for the task and some assumptions on how you would like to proceed additional.
  2. Looking within the region: 'I would prefer to hire a PHP Developer who belongs to my region' this can be the fact that the majority of the businesses think and work in this direction. Well, most of them think that this the simplest way; communication becomes straightforward, problems may be solved with ease and at a faster rate.
  3. Ignoring support and communication: Make sure that your communication is perfect. A proper mode of communication should be selected by the company for solving and reviewing the latest updates and problems. So, while interviewing, test their analytical, decision-making, and problem-solving ability, and also check whether the developer is able to understand and implement the requirements in the project easily or not.
  4. Pricing issue: Do you agree on variable pricing? You never know how much money are going to be spent throughout the process and how many months it would take for the website to go live. This problem arises when working with an offshore. So, in the first interview itself, talk about all the issues clearly. Make sure you provide the detailed contract which is duly signed by the offshore company.

What our users are discussing about PHP