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.

  • Devops Engineer for Transferring Website

    $27, Hourly | Maldives
    We are looking for a DevOps Engineer to help us in Transferring our web site from Fast Comet hosting to digital ocean hosting and do integration for...
  • Developer needed for making courier website

    $98, Fixed | Turkey
    I need a website developer who can make a website for me, It could be WordPress or any other platform doesn't matter, I need a website with in 15 days...
  • Web App Developer needed to create a series of web applications

    $24, Hourly | China
    We are looking for a Developer who can work with our Product Manager and develop Web Applications for our business, Enterprise DNA.We currently have t...
  • SEO friendly website developer required

    $7, Hourly | Iran
    We need our website re-designed and coded to 100% meet html standards and compliance for search engine submission and SEO.Site must be mobile responsi...
  • WordPress developer for site customization

    $29, Fixed | Haiti
    I have a website that needs an customization, I am looking for an entry level freelancer and my budget is tight for the job....The selected freelancer...
  • Setup MySQL table and Grocery CRUD

    $14, Hourly | United States
    I have a fresh server (on digital ocean) with setup and working LAMP. I need somebody who will set up my server following things:Setup MySQL table (us...
  • SuiteCRM automated Backup

    $16, Hourly | France
    We are looking to setup an automated SuiteCRM and database backup daily in the evening to run at 9PM PST. We want a local instance, a cloud instance t...
  • Software Developer Custom Web Application

    $24, Hourly | Mexico
    We have a desktop application that we are in the middle of converting to a web application. The current developer has not prioritized the development...

People also searched for

Guide to Hiring a Great NodeJS Developers
Guide to Hiring a Great NodeJS Developers
Web Development

In today’s online world, businesses are earning profit from interactive websites and scalable applications. As an owner of such a business, you must pay attention to the trending t...

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...

Learn Web Scraping using Python
Web Development

The importance of extracting information from the web is becoming increasingly loud and clear. Every few weeks, I realize myself in a situation where we need to extract information...

You are freelancing Ninja?

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

How to hire a php developer today?

Now days, Freelancing is simplest, easiest and best way to Hire PHP developers for full-time or part-time.

Once you've decided to hire dedicated PHP developer instantly, you need to follow some basic steps to Hire PHP developer for website design & development. The first place to start with is your outsourced project itself, define outline of your website concept with complete requirement and summarizing the vital elements and analyze your requirement for determine the employment type (individual/agency), budget and share your requirement on freelance platform. Within 24 hours you get top PHP developers proposals, you need to scan their portfolio and shortlisted them, preferred only experienced PHP developer because hiring experience person is always better deals. And finally invite them for interview to assess their abilities. If you aren't from a technical background, seek someone proficient to conduct a technical interview of PHP developers.

What are the benefits to hire a php developer near me?

Hire PHP developer 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 experts is a must for you if you want to build a best PHP based site with a professional look. Top 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. Top PHP developers for hire 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.

How to create a website using PHP for new company?

If you decide to create a website in PHP and you don't know PHP programming and website design. Freelance market is best choice for development of an attractive and fully functional website. You just focus on your business and define the primary purpose of your website, your specific user experience and fundamental goal of your website. Following points are step by step guide for creating a website for business.

  • Define primary goal and complete requirement of your website.
  • Define domain name, it is one of the most important features of your PHP website (i.e. URL).
  • Choose a great experienced PHP website developer for web page design.
  • Choose your favourite website template.
  • Test and publish your website.

What are php developers?

PHP (Hypertext Pre-processor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

PHP Programming Languages most commonly used for web site and web Application Development. PHP could be use for a general purpose, server-side scripting language run a web server that is designed to form dynamic pages and applications.

PHP as a web development option is secure, quick and a reliable that gives lots more advantages to form it accessible to a lot of people. It is to be given a thought on what has made PHP Programming as one of the most commonly programming language for the online business.

Mistakes while hiring the Top 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.

Users & Their Opinions About PHP

Freelancers You May Hire

Related Freelancers You May Like

Related Jobs

Related Services

Related 5 minutes reads from our blogs

How to Start Freelancing

Today we'll read about 5 amazing freelancing tips, I believe you have a lot of questions about How to go out freelancing? What is freelancing? & how to get your first project especially if you're a beginner in computer science and information technology. So, here are my top 5 freelancing tips for beginners. I have followed these throughout my freelancing career and this will surely help especially if you are a beginner or an IT or a computer science student.

Tip 1: Just Start

just for you - let's get started

The first step is just to start. You must be wondering, that’s not new. We know it. But, let me explain.

What is meant by “Just Start”?

If you are a beginner you don't have to be a master of a particular technology. Let’s take an example of “Web Development” even if you have a very basic understanding of HTML, CSS, and JavaScript, and if you are wondering whether you are ready enough or not, perfect enough or not, master in particular technology or language. One thing which I learned in my freelancing journey is if you're running behind perfection at a very beginner level then you'll never start freelancing, you are always underconfident and believe that I'm not sure, I'm not prepared and that thought will procrastinate your freelancing. What I'm trying to say is just start with whatever knowledge you have and then you can build on top of it. clear this out let me give you an example from my personal experience.


My first project was a portfolio website for a fashion designer. I and my friend had approached the client and he wanted a portfolio website. Ask was, he needed a website to upload photoshoot images on this website and it has to be a dynamic website. But, we did not know anything about a dynamic website. After graduation, we had started with a little bit of web development & learned something about HTML, CSS & JavaScript by YouTubing & Googling & we were confident about building a static portfolio website. But, we did not know how to develop a dynamic website where a user can put a lot of content every week?


Still, we took that order as a challenge for just 5000 INR, money was not our primary criteria. We wanted to learn and master the skills which we learned. We came home and googled and came across this concept of WordPress. WordPress is the content management system and we did not get into a lot of details but just the basics of it which were needed to deliver the project. It gives you a dynamic template where you can drag and drop pages, posts, etc, and create dynamic stuff.


Since WordPress is built in PHP, we started learning PHP because we did not know PHP at that time and basics of WordPress. So, we took that order even when we were not sure if we can deliver it or not We just did it. And after learning WordPress we did that website & deployed …. Yes, it worked out pretty well. So when I say just do it I mean you don't have to be an expert in any kind of domain so this was just web development. Let’s see you are getting into software or android app development. You don’t have to be an expert you just need to start that’s why tips no. 1 just started.


Tip 2: Start With Contact -

To start with your contacts - you must be thinking about how am I going to start! And you must be very excited about this but you would be like:

Where do I get my first contact?

Where do I get my first business?

Where do I get my first freelance order?


The best way to start is your contacts, family, friends, mutual friends, or long-distance family members who ever have a business.


Why you should start with your family and friends?

The level of risk is low. When you are approaching a random person the risk of you making a mistake in the project is very high, the stakes are high. If your relative or your uncle is having a business…. this is just one example… let's say he is a chartered accountant and he has his firm, you can approach him and tell him that you are into web development and want to develop a website for his firm so and so the amount of time will require and probably want to charge or not. I would not recommend that you charge for the first time maybe. Especially if he or she is your family member but, you can do it if you feel and he/she is okay with this. I am not saying that you should not charge. But, the stakes will be very less, the risk will be very less because he or she is your family member or he/she is a friend. Even if you make a mistake or the time gets delayed you can still get off easily if you doing it for the actual client than you can get into some trouble.


The best way to start is with your friends and trust me guys a lot of your friends and family members definitely must be having some kind of business for which they want to develop a software or website and we can.


Tip No 3: Team Work

The next tip is related to the team. Now in teamwork, you need to form a team, you need to collaborate, to Partner up. You are ready to make your first move into the freelancing world. You're going to start with your contact, relatives, or maybe your own parent’s business.


Feeling a lack of confidence! - The best way to overcome just to make a partner with your friend. He has experience of a few months or years and proceeds for the web development in which you want to develop a website for your own family. Your Dad or Mom has business and wants to develop a website for that. For example, If your Mom or Dad is a dentist or a doctor and he or she has her clinic & you want to develop a website for that clinic.


What you can do?

You can approach your friend who is also into web development and you can tell him you know I'm trying to develop a website let's do it together, the biggest advantage of this is that you will have one more smart mind working on the project. When you have one or more than one mind working on a project there is a lot of knowledge transfer happening between the two. If you are stuck in some module maybe your friend can resolve that or vice versa. Maybe he or she is stuck in some problem and you can resolve it. The speed of the development increases and the success rate also increases and you'll learn a lot from your friend and one more amazing thing that you can learn how to work in a team. When you go to start your corporate career after education you already have a good knowledge and experience of working as a team. You can get more experience by freelancing and by collaborating with others.


Teaming up is important it will also boost your confidence because the risk has been dived, the work divided among the members or your partner and that will give you more confidence.


Tip 4: Get Social –

It is not essential but it will help you when you want to grow your business or freelancing project.


Spend some time on digital media that is social media platforms. Create a Facebook page, Instagram page, small blogger website If you can. But, I would recommend this because creating a social media page will help you than your friends, family. It will help you reach out to the world. You might feel there is a lot of negativity like people will say you will get addicted to Facebook, Instagram, etc but, use these platforms as your career development tools. Even YouTube is a social media platform where you can watch a lot of information, you need to use it for your benefit in a positive way. Being social is very important, you might get your next project or freelance order from the social media platforms as you move ahead.


Once you have exhausted your list of contacts, list of family members you can go social you can promote your pages promote your work online, and that would help you a lot and creating a digital identity on social media creating a website, blog, the page gives it a professional look.


Tip 5: Be Jack Of All

It’s not exactly a tip but it will help you if you are a beginner. The tip is you need to be the jack of all and king of none.


When you start your freelancing career, assuming that you are a college student or IT student and you haven't gotten into the corporate world and you don't have a lot of experience. If this is the case I would suggest you try different technologies rather than focussing on just one. If you want to become a master of PHP and you are… you know that technology keeps on changing a lot of things become outdated and new technologies keep on coming.


What if PHP gets outdated? –

The first start with PHP then try ASP.NET as well then JavaScript this was for web development, You need to diversify yourself and knowing each and everything, at least the fundamentals. You don't have to be a master of one at least the beginner’s level but you need to know a lot of things on a fundamental level this reduces the risk. If tomorrow any of gets outdated you can easily switch to another. After completing your education you will be ready to work in corporate scenarios & where you will work on one particular technology. Learn more every day because it's always good to have a more technical background by which you can switch between your jobs.


It's not necessary to be a master in one particular technology at a beginner's level. I would not suggest it to you because I never did that. what did I do? I started with web development with PHP then I moved on to ASP, I also worked on software development, windows form application development using c – sharp. I was not an expert in java but later on, moved on to iOS & Android app development for mobile app development. Lot of things I've tried out and now going to be a master of one.


These are my 5 tips to start a freelancing career as a beginner. If you have any questions or need help, you can reach out to me in the comment box below. I will respond to all queries in the comments.

Turn Past Failure into Future Success

 Many of you must have seen my posts on Toogit wall and on the home page of Toogit, yes, I am Shilpi Goyal one of the featured freelancer on Toogit. I receive a lot of queries on my social media and Quora about how did I find my success in freelancing. But, I always wanted to tell you guys my more

Which Language is Better For Writing a Web Crawler? PHP, Python or Node.js?

I want to share with you a good article that might help you better extract web data for your business. Yesterday, I saw someone asking “which programming language is better for writing a web crawler? PHP, Python or Node.js?” and mentioning some requirements as below. The more

How to secure a WordPress Business Website

Your website is a crucial part of your business. And if its in wordpress, you need to pay extra attention to your WordPress website security. Here are some of the best WordPress website security practices that will improve your WordPress security and keep your site safe from hackers and more