Guide to PHP error reporting in 2019

 Guide to PHP error reporting in 2019

Guide to PHP error reporting in 2019

PHP has been around for quite a while and has developed its own quirks and characteristics. It has also developed its own flavor of error reporting, which is fairly straightforward. In this post, we’ll show you how easy it is to add error monitoring for PHP.

What is a PHP error?

A PHP error is a data structure that represents something that went wrong in your application. PHP has some specific ways you can invoke errors. One easy way to simulate an error is with the die() function:

die("something bad happened!");

This will end the PHP program and report an error. When a program is ended, this is what we would call a fatal error. You’ll see later that we can control how exactly the error is handled, in case we need to invoke some cleanup logic or divert where the error reports. You can also simulate this with the trigger_error() function:

<?php

trigger_error("something happened"); //error level is E_USER_NOTICE

//You can control error level
trigger_error("something bad happened", E_USER_ERROR);
?>

This will trigger a nonfatal notice in the system by default. You can override the error level if you need a more severe error.

There are actually two forms of errors in PHP: standard run-of-the-mill errors, and exceptions.

Exceptions were introduced in PHP 5. They give you easier semantics like try, throw, and catch. It’s easy to throw an exception. This follows along with the great success statically typed languages, like C# and Java, have had with them.

throw new Exception("Yo, something exceptional happened);

Catching and throwing exceptions tend to be more streamlined than the more traditional PHP error handling. You can also have more localized error handling, as opposed to only handling errors globally via seterrorhandler(). You can surround specific logic with try/catch blocks that only care about specific exceptions:

<?php try {
    doSystemLogic();
} catch (SystemException $e) {
    echo 'Caught system exception ';
}

try {
    doUserLogic();
} catch (Exception $e) {
    echo 'Caught misc exception ';
}
?>

How to enable error reporting in PHP

Enabling error reporting in PHP is dead easy. You simply call a function in your script:

<?php
error_reporting(E_ALL);

//You can also report all errors by using -1
error_reporting(-1);

//If you are feeling old school
ini_set('error_reporting', E_ALL);
?>
This says “please report errors of all levels.” We’ll cover what levels are later, but consider it a category of error. So it’s essentially saying “report all categories of errors.” You can turn off error reporting by setting 0:<?php
error_reporting(0);
?>

The method parameter in error_reporting() is actually a bitmask. You can specify different combinations of error levels in it using this mask, as you can see:

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
?>

This says “report fatal errors, warnings, and parser errors.” You can simply delimit by “|” to add more errors. Sometimes you may want more advanced error reporting settings. You can leverage bitmask operators to report on a variety of criteria:

<?php
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>

As you can see, you have quite a bit of flexibility in determining what errors to report. That does beg the question: what types of errors and exceptions are there to report on?

How many error levels are available in PHP?

There are a whopping 16 error levels in PHP 5. These errors represent the category and sometimes severity of an error in PHP. There are a lot, but the numerous categories let you easily identify where to debug an error from its level alone. So, if you wanted to do something specific only for user errors, like input validation, you can define a condition handler for anything starting with E*USER. If you wanted to ensure you shut down a resource, you can do that by clueing into errors ending with *ERROR.

Errors in PHP are for the most part categorized by their severity (error warning, notice) and source (user, compiler, runtime).

I want to hone in on a few popular ones here.

First up, we have the general errors:

  • E_ERROR (Value 1): This is the quintessential fatal error. If you see this bad boy, your app is done for. Restart and try again.
  • E_WARNING (2): These are errors that don’t crash your app. Most errors seem to be at this level.

Next, we have user errors:

  • E_ERROR (Value 1): This is the quintessential fatal error. If you see this bad boy, your app is done for. Restart and try again.
  • E_WARNING (2): These are errors that don’t crash your app. Most errors seem to be at this level.

The final category of note is the app lifecycle errors, usually with “core” or “compile” in the name:

  • E_ERROR (Value 1): This is the quintessential fatal error. If you see this bad boy, your app is done for. Restart and try again.
  • E_WARNING (2): These are errors that don’t crash your app. Most errors seem to be at this level.

There are a few other errors. You can find the entire list of them here.

PHP display errors

In PHP, you can decide whether or not to display errors. This is different from reporting them. Reporting them will ensure the errors are not swallowed. But displaying them will show them to the user. You can turn it on with the displayerrors and displaystartup_errors directive:

<?php
 ini_set('display_errors', 1);
 ini_set('display_startup_errors', 1);
?>

Turning these on will ensure they show up in the body of the web response to the user. It’s usually a best practice to turn these off in nondevelopment environments. The integer method parameter is also a bitmask, like in error_reporting(). The same rules and options for that parameter also apply here.

What is a PHP warning?

You’ll note above that one of the error levels is E_WARNING. You may also have noted that many of the error levels have warning versions. I want to dig into this a bit. The main difference between a warning and an error in PHP is whether or not it ends the application. In PHP, most errors don’t actually stop the script from executing.

Here’s an example:

<?php
 $x = 1;
 trigger_error("user warning!", E_USER_WARNING);
 $x = 3;
 echo "$x is  ${$x}";
?>

You will still see $x is 3 despite triggering the warning. This can be useful if you want to collect a list of validation errors. I personally prefer to use exceptions these days, but your mileage may vary.

How Crash Reporting helps

PHP makes it easy to set up external error reporting tools, like those offered by Raygun. It provides a few different hooks into its runtime to handle errors and send them over the wire. See this example, torn from Raygun’s PHP page:

namespace
{
    // paste your 'requires' statement

    $client = new \Raygun4php\RaygunClient("apikey for your application");

    function error_handler($errno, $errstr, $errfile, $errline ) {
        global $client;
        $client->SendError($errno, $errstr, $errfile, $errline);
    }

    function exception_handler($exception)
    {
        global $client;
        $client->SendException($exception);
    }

    set_exception_handler('exception_handler');
    set_error_handler("error_handler");
}

First, we declare the client, using an API key for security:

    $client = new \Raygun4php\RaygunClient("apikey for your application");

Then we create a couple of functions that handle our errors and exceptions:

   function error_handler($errno, $errstr, $errfile, $errline ) {
        global $client;
        $client->SendError($errno, $errstr, $errfile, $errline);
    }

    function exception_handler($exception)
    {
        global $client;
        $client->SendException($exception);
    }

Note we call the SendError() function, passing in a few relevant details about the error data structure. This will make a remote call to Raygun.

Finally, we hook these into PHP’s runtime by globally handling both traditional errors and the newer exceptions:

set_exception_handler('exception_handler');
set_error_handler("error_handler");

And that’s it. With this all in place, we can get beautifully formatted error reporting that can look like this:

Wrapping up PHP error reporting

As you can see, PHP error reporting is straightforward. You can trigger exceptions through special functions. You can also trigger exceptions, like in other typed languages.

PHP Interview Questions with Solutions: Prepare for PHP Interview

PHP Interview Questions with Solutions: Prepare for PHP Interview

Prepare for PHP Interviews. Set Variable With php.ini File. Logic & Output Behind PHP Code Segment. Class Concept, Error & Functions in PHP. Start PHP Now!

Description
In this course you will be introduced with some tricky questions that everyone face during their interview. In each solutions I have included some useful functions which we generally use at the time of development also. I have covered the following area in my course with Questions, Attractive Presentations and Practical Solutions that will help you to understand the logic behind PHP in a different way.

Some useful functions
PHP error types
Class concept
Access specifiers public, private and protected
Set variable with php.ini file
Operators introduced in PHP7
Logic and its output behind some code segment
Basic knowledge
PHP7, XAMPP Server, Notepad++
What will you learn
This course is build for the person who is facing interviews. Every question is well explained with the practical solution through videos. So that everybody can prepare themselves for the tricky questions asked during interviews
To continue:

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

PHP Programming Tutorial | Online PHP Certification Training

PHP Programming Tutorial | Online PHP Certification Training

Knowledge of PHP, the most popular back end language on the web can be yours, all at $9! Supplement your knowledge of html and JavaScript and add value to your CV. This course from Simpliv will make you a lot more employable in the market. Begin to take strides in your development career!

Description
This completes it.

PHP is the stepping stone to your first professional development gigs

PHP is the most popular back end language on the web.

Companies like Facebook and Tumblr use PHP as their primary back end coding language. It's in universal demands, and, as a new developer you're expected to know you're way around the front end and the back end. That's where PHP comes in.

There was a time when a web developer could get away with knowing just HTML and some Javascript, but now as employers are looking for more value, you have to know more. PHP lets you access an entire world of backend databases, like mySQL which is introduced in this course.

FACT: With PHP knowledge you'll be able to complete more advanced projects and be more employable.

People ask all the time: What's the best past to becoming a professional developer?

People going in to web development need two types of technical knowledge. First, they need to know how to manipulate content in a browser. That's where HTML5 and Javascript come in. But they also need to be able to interact with backend systems like eCommerce systems, databases and content management systems.

With PHP, developers:

Create systems by which data can be stored and retrieved in a database
Interact with eCommerce systems facilitating sales, credit card processing and shipping all over the world
Create complex content and customer management systems customized for industry use.
Create plugins and customizations for the most the most popular content management systems in the world, Wordpress, Drupal and Joomla (all of which are written in PHP!)
Who is the target audience?

New developers who want to add PHP to their tool aresneal
Web Designers who want to start writing code
Teachers and students
Current developers who need to learn PHP
Basic knowledge
Successful students in this course have a working knowledge of HTML
Successful students in this course can work with web browsers to navigate the internet
This course works on Mac or PC or even Linux with a few modifications
What will you learn
Set up a PHP Web Server
Integrate PHP with HTML code
Call PHP Pages from HTML
Use the echo() and print() functions
Integrate HTML with echo() and print() functions
Declare and use constants
Declare and initialize PHP variables
Understand the type of values held in PHP variables
Use arithmetic operators to perform math functions
Use comparison operators to make logical comparisons
Understand basic if statments
Create complex if statements which facilitate multiple outcomes
Use the PHP switch statement
Work with while loops.
Identify when a do while loop is appropriate and use it
Code a for loop
Create simple arrays
Use a for...each statement to loop through an array
Create associative arrays
Understand and use multidimensional arrays
Identify and use the superglobal arrays included in PHP
Use string functions to manipulate strings
Convert strings to arrays and vice-versa
Use hashes and encryption to enhance application security
Write simple functions
Write functions that take arguments and return a value
Read and write text files to the server
Read, write and parse CSV files
Set, read and delete cookies
Create sessions
Pass session variables between PHP pages
Expire sessions as required
Send plain text and HTML emails using PHP
Use a database to create a complete CRUD app
Store data in the database
Retrieve data from the database
Modify and delete database data
To continue: