Error Handling in PHP
I want to stop or block error, warning messages for only one operation?
or
How to restrict error message for specific functions?
Explanation
Some times we will have to block warning message for certain operations.
It can be done very easily.
Stop error reporting for specific operation in PHP:To stop error or warning messages on web pages for certain method or operation you can use the character "@"
For example, here we try to open a file that does not exit, and call a include with a wrong file name, we will get warning messages as below
Code Used: e.g:
<?php
echo("test for error message 1");
fopen('test.txt',r);
echo("test for error message 2");
include "test.php";
?>
Result: test for error message 1
Warning: fopen(test.txt) [function.fopen Previous]: failed to open stream: No such file or directory in /restrictErrors.php on line 75
test for error message 2
Warning: include(test.php) [function.include]: failed to open stream: No such file or directory in /restrictErrors.php on line 77
Now with the same code we will restrict or stop error reporting for one operation say include call. To restrict errors, we have to use the character @ before the function. i.e instead of
include.... we will use
@include.... Code Used: e.g:
<?php
echo("test for error message 1");
fopen('test.txt',r);
echo("test for error message 2");
@include "test.php";
?>
Result: Warning: fopen(test.txt) [function.fopen]: failed to open stream: No such file or directory in /restrictErrors.php on line 104
test for error message 2
Thus we can prevent the errors and warnings from being shown on the web page.