Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Debug PHP Code – Ninja Techniques You Should Know

INTRODUCTION
MOST UNENJOYABLE PROCESS

Welcome to a tutorial on how to debug PHP code. Finding bugs and squishing them is probably one of the most dreadful parts for a programmer. Especially when the Error messages do not offer any help at all – Either when they don’t make any sense, or don’t point out where the exact error is at.

While there are a ton of different tools and gimmicks for debugging, but we are not going to use any of those. This guide will be touching more on the “universal debugging techniques” so that everyone can adopt regardless of the editor or platform. So, just how do we debug PHP code? Read on to find out!

I have included a zip file with all the Example source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Basics

Section B
Types of Errors

Section C
Debugging Techniques

Extra
Download & More

Closing
What’s Next?

SECTION A
THE BASICS

Before we dive into the debugging techniques, let us start with some of the basic stuff that you have to know… Please feel free to skip this section if you are already an advanced code ninja.

Yes, we can actually disable error messages in PHP, and some of you beginners are probably confused to why we do such a “silly thing” to disable them. Is it not better to show the error messages? If we disable error messages, then how the heck do we know when errors happen?

Well, you need to understand the world of software development a little more. In the development side, we can show all kinds of error messages we want, it is better when developers and testers pick those up.

But when it comes to actual production systems, some people choose to hide the error messages for a “graceful system”, so that it “crashes gently and quietly”, without scaring users away. So now that you know, don’t switch on the error display in production systems, unless you really have to.

ERROR SETTINGS

Now, following up on “how do we know if errors have occurred”, there are 6 settings in the php.ini file that you have to know first:

php.ini
display_errors = On
error_reporting = E_ALL
display_startup_errors = On
html_errors = On
log_errors = On
error_log = PATH/ERROR.LOG
  • display_errors Show the error messages on the screen.
  • error_reporting Types of errors to show if display_errors is on. Will go through more of this below.
  • display_startup_error This one displays startup errors, not runtime errors.
  • html_errors Format the error messages in HTML format?
  • log_errors Keep errors in a log file.
  • error_log Where to keep the error log file.

So typically:

  • We go “full force all error reporting on” a development server.
  • Hide with display_errors = Off but log_errors = On a production server – That is how we can still track errors, from an error log file.

ERRORS REPORTING LEVELS

We can set the level of reporting with error_reporting, and there are generally 3 “main levels”:

  • E_ERROR Fatal errors.
  • E_WARNING Warnings, non-fatal errors.
  • E_NOTICE Notices, non-fatal.
  • E_ALL All kinds of errors.

Take note that the above is not all to it, check out the official PHP manual for the full list. But for now, we can play with the above to tweak the level of reporting:

php.ini
; Report all errors
error_reporting = E_ALL

; Report critical errors only
error_reporting = E_ERROR

; Report critical errors and warnings
error_reporting = E_ERROR | E_WARNING

; Report all errors, except notices
error_reporting = E_ALL & ~E_NOTICE 

SECTION B
TYPES OF ERRORS

Once you have enabled error reporting on your machine, PHP should throw some error messages – Which should give you a good hint as to what went wrong and how to fix it. Here are the types of common errors to look out for.

FATAL ERRORS

Fatal errors will abruptly stop the script and break the system – There is simply no way that you can miss fatal errors. Even if the error reporting is turned off, a weird broken script is just going to raise eyebrows. Fatal errors commonly include undefined functions and missing files.

error-1-fatal.php
Fatal error: Uncaught Error: Call to undefined function doesnotexist() in D:\http\test\error-1-fatal.php:2 Stack trace: #0 {main} thrown in D:\http\test\error-1-fatal.php on line 2

SYNTAX ERRORS

Stupid things such as missing a semi-colon or comma. 

error-2-syntax.php
Parse error: syntax error, unexpected ‘$hello’ (T_VARIABLE) in D:\http\test\error-2-syntax.php on line 3

WARNINGS

Warnings are non-critical errors, but still of significant importance. For example, putting a string into a function that seemingly needs numbers instead – While this will not break the system, it might end up with the wrong results.

error-3-warn.php
Warning: A non-numeric value encountered in D:\http\test\error-3-warn.php on line 3

NOTIFICATIONS

One of the most annoying kinds of “errors”. Notifications are often of little importance, and they are just here to remind you of stuff like “you have not defined this before”, or “this has been deprecated, not recommended”.

error-4-notify.php
Notice: Undefined index: foo in D:\http\test\error-4-notify.php on line 2

SILENT ERRORS

There are truly deadly errors. They do not throw any error messages, are hard to spot, and will continue running. You will only realize that there is an error when the scripts do not produce the kind of results that you want. For example, a small typo mistake can result in a significant “silent error”.

error-5-silent.php

SECTION C
DEBUGGING TIPS & TECHNIQUES

Now that you know all the basics, let us dive into some of the ninja debugging tips and techniques.

RUNTIME ERROR REPORTING

If you really need to display the errors on the productions server, and only for a particular script – Yes, we can do that with a few lines of ini_set and error_reporting.

1-display-error.php

Just remember to remove these lines after you get a screenshot of the error message.

DUMP THE VARIABLES

So, what is in an array? What is in the session that is causing problems? print_r and var_dump are your best friends.

2-var-dump.php
 [
    "name" => "Foo bar",
    "qty" => 99
  ],
  "234" => [
    "name" => "Doge",
    "qty" => 88
  ]
];

// What is in the session?
print_r($_SESSION);
// More details using var dump
// var_dump($_SESSION);
?>

CODE SECTIONING, DIVIDE AND CONQUER.

Try to write your code in sections – This is not just a debugging technique, but also a good practice. Remember the silent errors? Trying to find that small typo error is exactly like looking for a pin in an ocean of code.

But when we section our code, we can use echo, print_r, or var_dump to manually confirm the values and output at each section of the code. Use this in conjunction with die() or exit() to stop the script at each section – Slowly moving to the next section only when we confirm the output is correct at each stage.

3-halt-section.php

USE A GOOD EDITOR OR IDE

This is not a technique, but quite a common sense thing. A good code editor will highlight all the errors as you type, even help you to format the code. This will filter out all the silly mistakes, such as missing semi-colons.

CUSTOM ERROR LOG

Remember from earlier that we can log the errors “in the background” to a file with log_errors and error_log? Well, we can actually use the error_log() function in PHP to manually create an error entry. For example, we have a script that will connect to another server, and this will log an error entry when the connection fails.

4-error-log.php
 "https://DOES-NOT-EXIST.com/dummy.php",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HEADER => false
]);
$result = curl_exec($curl);
if ($result === false) {
  // ERROR LOG
  error_log("Failed connecting to https://DOES-NOT-EXIST.com", 0);
} else {
  // OK
}
curl_close($curl);
?>

Very useful if you want to monitor certain things or even the reliability of certain services. By the way, we can even send notification emails with error_log(), check out the official PHP manual for more options.

GRACEFUL FAILURES

When PHP throws an error, it’s not the end of the world. This should be in most of the basic tutorials, but a quick recap – With a try-catch-finally block, we can gracefully handle the exceptions.

5-graceful.php
 PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES => false
    ]
  );
}

// ERROR - DO SOMETHING HERE
// THROW ERROR MESSAGE OR ALTERNATIVE
catch (Exception $ex) {
  print_r($ex);
}
?>

SUPPRESSING ERROR MESSAGES

Finally, this is not really related to debugging, but we can suppress error messages by adding a @ in front of the functions. For example, when we open a non-existent file:

6-suppress.php

EXTRA
DOWNLOAD & MORE

That’s all for this guide, and here is a small section on some extras that may be useful to you., plus the download link as promised.

INFOGRAPHIC

Common PHP Errors (click to enlarge)

SOURCE CODE DOWNLOAD

Click here to download the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT? DO WE NEED DEBUGGING TOOLS?

Thank you for reading, and we have come to the end of this guide. Debugging, troubleshooting, and handling errors can seem to be a little intimidating at first. But once you catch the gist of it – It really is nothing more than tracing the code to find out how, what, and where went wrong.

As to the many tools available in the market… If it helps you, then it is good. But personally, I have survived without any tools since the stone age of PHP; The error messages and logs give good enough hints as to where went wrong.

I hope this guide has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Debug PHP Code – Ninja Techniques You Should Know appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Debug PHP Code – Ninja Techniques You Should Know

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×