PHP - Remove warning and notice

error_reporting function in PHP allows  to tell which errors to report.

For example, if we want to display all error messages except warnings, we can use the following line of code:

//Report all errors except warnings.

error_reporting(E_ALL ^ E_WARNING);

Typically speaking, the error_reporting function should be placed at the top of your code. This is because the function can only control errors that occur in the code below it.

If you also want to hide notice messages, then you can set the following level in the error_reporting function:

Stopping warning messages from being displayed.

If you simply want to stop warning messages from being displayed, but not prevent them from being logged, then you can use the following piece of code:

**********************************************

//Tell PHP to log errors

ini_set('log_errors', 'On');

//Tell PHP to not display errors

ini_set('display_errors', 'Off');

//Set error_reporting to E_ALL

ini_set('error_reporting', E_ALL );

***********************************************

Here, we are using PHP’s ini_set function to dynamically modify the settings in our php.ini file:

1- We set log_errors to On, which means that PHP will log warnings to our error log.

2- We set display_errors to Off. As a result, PHP will not output errors to the screen.

3- Finally, we set error_reporting to E_ALL.

Using the @ character to suppress errors.

In some cases, you might not have control over certain warnings.

For example, a GET request to an external API could fail, resulting in a “failed to open stream” warning. To prevent this from occurring, we could use the @ character like so:

//API URL

$url = 'http://example.com/api';

//Attempt to get contents of that URL

$result  = @file_get_contents($url);

As you can see, we have placed the @ (AT) character next to our function call. This means that if file_get_contents fails, it will not throw an E_WARNING message.

This works because the @ character is an error control operator that tells PHP to ignore any errors.

Note that error suppression should be used sparingly. Abusing this control operator can lead to issues that are difficult to debug.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...