Showing posts with label PHP error_reporting. Show all posts
Showing posts with label PHP error_reporting. Show all posts

Friday, 2 August 2019

Tuesday, 11 September 2018

Replace error reporting with exception handlers with PHP

As part of a series of posts about PHP exception handling, this post looks at how to make regular errors use exception model. Normally only the newer object-oriented extensions throw exceptions but it is possible to make all errors throw an exception instead using set_error_handler.

Normal behavior

The normal behavior for a normal error is to show an error message which cannot be handled by the try...catch syntax. For example, if error reporting is E_ALL and we try to access a variable which has not yet been set:
error_reporting(E_ALL);
echo $x;
This is what will be displayed:
Notice: Undefined variable: x in [filename] on line [line number]

Bind errors to the ErrorException handler

Instead of this default error behavior, errors can be bound to the ErrorException handler like so:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
What this is doing is replacing the default error handler with our own function which in turn throws an ErrorException. Now when we try to use the same variable above that has not been set an exception will be thrown, looking something like this:
Fatal error: Uncaught exception 'ErrorException' with message 'Undefined variable: x' in [filename]:[line number]
Stack trace:
#0 [filename]([line number]): exception_error_handler()
#1 {main}
  thrown in [filename] on line [line number]
This could now instead be handled inside a try..catch block like so:
try {
    echo $x;
}
catch(Exception $e) {
   
}
Obviously you wouldn't be trying to catch such a trivial exception example; it's just to illustrate the other examples on this page which deal with a fairly trivial error. You could then potentially use an exception handler to deal with these sorts of exceptions, instead of having to have separate error handlers and exception handlers.

Exception Series

This is the fourth post in a weekly series of six about PHP exceptions. Read the previous post "Catch uncaught exceptions with PHP", the next post "Extend PHP's exception object" and use the links below to subscribe to my RSS feed, by email, or follow me on Twitter or Facebook to keep up to date with my daily postings.

Related posts:

Get and modify the error reporting level in PHP

PHP's error_reporting() function allows a script to check what the current error reporting level is and/or modify it. I wouldn't normally recommend changing the error reporting level programatically, but there may be times when it's needed. The nice thing is it's easily possible to get the current level, change it, and then set it back to what it was previously.

Getting the current reporting level

To get the curent reporting level simply call the error_reporting() function without passing any parameters, like so:
$current_error_reporting = error_reporting();
This will return an integer value. You can see for example if E_NOTICE is set in the error reporting level like so:
if($current_error_reporting & E_NOTICE) {
    // do something
}

Changing the error reporting level

To change the error reporting level to something different, pass the new level as the parameter. The value return from the function call is the old error reporting level. The following example changes the error reporting level to everything but notices and stores the old level in a variable.
$old_error_reporting = error_reporting(E_ALL ^ E_NOTICE);
The old error reporting level could then be restored at a later time:
error_reporting($old_error_reporting);

Removing notices from the current reporting level

This final example removes E_NOTICE from the current reporting level, runs some other code, and then restores the old level back again.
// remove E_NOTICE from error reporting and store previous value
$old_error_reporting = error_reporting(error_reporting() ^ E_NOTICE);

// run some other code
// ... code ...

// restore old error reporting level
error_reporting($old_error_reporting);
The above can be tested using the following code. It sets the error reporting level to E_ALL at the start so we can be sure when testing what the initial value is:
error_reporting(E_ALL);
echo error_reporting(), "\n";

$old_error_reporting = error_reporting(error_reporting() ^ E_NOTICE);
echo error_reporting(), "\n";

error_reporting($old_error_reporting);
echo error_reporting(), "\n";
This outputs
6143
6135
6143
which is to be expected: 6143 is E_ALL and 6135 is E_ALL without E_NOTICE. 

Related posts:

Work out PHP's error reporting from an integer value

This post has some example PHP code which can be used to work out which error_reporting levels are reported and which are not from an integer value.

PHP code

Either use the $error = error_reporting() line to work out the error reporting levels for the current setting, or use a hard-coded value, replacing 22527 in the example code with the value you want to decode. Replace \n with <br> tags if it's being rendered on a webpage, or save the output to a variable if writing to file or emailing etc.
//$error = error_reporting();
$error = 22527;

$levels = array(
 E_ERROR => "E_ERROR",
 E_WARNING => "E_WARNING",
 E_PARSE => "E_PARSE",
 E_NOTICE => "E_NOTICE",
 E_CORE_ERROR => "E_CORE_ERROR",
 E_CORE_WARNING => "E_CORE_WARNING",
 E_COMPILE_ERROR => "E_COMPILE_ERROR",
 E_COMPILE_WARNING => "E_COMPILE_WARNING",
 E_USER_ERROR => "E_USER_ERROR",
 E_USER_WARNING => "E_USER_WARNING",
 E_USER_NOTICE => "E_USER_NOTICE",
 E_STRICT => "E_STRICT",
 E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
 E_DEPRECATED => "E_DEPRECATED",
 E_USER_DEPRECATED => "E_USER_DEPRECATED"
);

echo "Report on:\n";
foreach ($levels as $level => $description) {
 if ($level & $error) {
  echo "$description\n";
 }
}

echo "\n";

echo "Do not report on:\n";
foreach ($levels as $level => $description) {
 if ($level & ~$error) {
  echo "$description\n";
 }
}

Example output

Report on:
E_ERROR
E_WARNING
E_PARSE
E_NOTICE
E_CORE_ERROR
E_CORE_WARNING
E_COMPILE_ERROR
E_COMPILE_WARNING
E_USER_ERROR
E_USER_WARNING
E_USER_NOTICE
E_RECOVERABLE_ERROR
E_USER_DEPRECATED

Do not report on:
E_STRICT
E_DEPRECATED

Related posts:

Friday, 3 October 2014

is_null in PHP

is_null — Finds whether a variable is NULL


Syntax: 
bool is_null ( mixed $var )

Finds whether the given variable is NULL.
Parameters: 

var

    The variable being evaluated.

Return Values:

Returns TRUE if var is null, FALSE otherwise.
Examples:

Example #1 is_null() example
<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>

Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

Thursday, 4 September 2014

PHP: What is the best way to remove or turn off warning messages in PHP?

There will be times when you will see a warning message output to the browser after running your PHP script and you may want to turn off that warning message. Obviously, it’s a lot better to get to the root of the problem and fix that instead. But, if you know that you do not need to fix the root of the problem (for whatever reason), in order to remove a warning message in PHP all you have to do is use the error_reporting function in PHP. If you don’t care about how the function works, then just skip to the section that says “The code to turn off error messages in PHP” to see the code that you should use to turn off warning messages in PHP. Otherwise, keep reading.

Using the error_reporting function to turn off warnings in PHP

The error_reporting function in PHP basically allows you to set the kind of error reporting that you want. How does the error_reporting function work? Well, you simply pass in the type of errors to the error_reporting function that you want to have reported on the page – you need to pass in constants (which are text fields that translate to numbers) to the error_reporting function .
The E_PARSE constant tells PHP that compile time parse errors should be reported and displayed on the page as you can read about here. Since you definitely want to know about any compile time errors, you should pass this constant to the function. The E_ERROR constant tells PHP that the details of any fatal run-time errors should be reported and displayed – this is also something you definitely want, since you should always know what the cause of any fatal run-time errors is.
Now that you understand a bit more about how the error_reporting function works – here is the actual code to use:

The code to turn off error messages in PHP:

You have to place this line of code before the code that is causing the warning to be displayed. If you place this code after the offending code, then it will not work in suppressing the error message that gets displayed. Here is the line of code to use:
error_reporting(E_ERROR | E_PARSE);

The code above does not have the E_WARNING constant being passed in

Because the function above does not include the “E_WARNING” constant, the non-fatal run-time warnings will not be displayed on the page when a PHP script is run. And that is exactly what prevents the warning message from appearing on the page.

How do the constants work in the error_reporting function?

In the example above, E_PARSE and E_ERROR are both constants – which means that they are actually numbers represented by text, so E_PARSE really is just some text that represents the numeric value of 4, and E_ERROR is text representing the numeric value of 1. Read on to understand how those constants work.

How does the OR operator work with error_reporting function?

Note that the function above uses the “|” – the OR logical operator, which is applied against the constants that are passed into the error_reporting function. You will notice if you look at this page that those constants are all multiples of 2 – the reason for this is because when they are “OR’ed, the appropriate bits will be retained and that will tell the error_reporting function what errors need to be displayed.

Another way to hide or remove warning messages in PHP

Another option to remove warning messages in PHP is to use what is called the error control operator – which is basically just the at sign – the “@”. When the “@” sign is put in front of an expression, any error message that might be generated by that expression will be ignored.
The “@” error control prefix operator will even disable error reporting for critical run time errors. For this reason, you should only use this operator if you really know what you are doing. The “@” can only be used in front of expressions – so it can not be used in front of a function or class definition, a for loop, etc. But, it can be used in front of a call to a function. Here is what it would look like in that scenario:
@someFunctionCall( );