good evening,
how to set custom error OR prevent page damage when display_errors=0 AND the page have errors AND i do not know what ‘condition, code, etc…’ will cause these errors ?
for example, in this code :
<?php
/////////////////////////////////////////////
ini_set("display_errors" , "0");
/////////////////////////////////////////////
$html = '
<table>
<tr>
<td><img src="img0.gif" /></td>
<td><img src="img1.gif" /></td>
<td><img src="img2.gif" /></td>
</tr>
</table>
';
/////////////////////////////////////////////
$dom = new domDocument();
$dom -> loadHTML($html);
$xpath = new domXPath($dom);
/////////////////////////////////////////////
$query = $xpath->query('.//table/tr/td');
$image = $query->item(1000000000); // <<---- item number
$img_src = $image->getElementsByTagName('img')->item(0)->getAttribute('src');
echo $img_src;
/////////////////////////////////////////////
?>
in that code because there is no item(1000000000), so it will cause error ..
and bacause display_errors" , "0" all errors will be hidden and the page be damaged
So, how to prevent that damage ?
i know i can prevent it by adding simple condition like :
if( $image <1 ){ die('error msg'); } before $img_src var
but what about if i have a big code more thane 10000 line and i do not know exactly what code will cause error !!
can we prevent it by httaccess ? by checking page source if it empty redirect to error page ..
or can we prevent it by some functions in php itself ?
any ideas ?
You can use set_error_handler . To set a callback ion case of error and in there you can terminate the script from executing further.
Update
Just found out custom error handler does not work with E_ERROR and other error types. This is in PHP Documentation
So this is a workaround that I found on internet and I have tested it with your script and is working fine.
Add the following code to the start of your script:
This registers a shutdown function which is executed on script termination from a fatal error, irrespective of whether display_errors is on or off.
And there we check if last error was a fatal one, if so we redirect to error_page.php.
Note: One thing to note is that the redirect is STILL working if display_errors is ON. I have tested it and it is working fine. This maybe because of output_buffering being enabled on my server though.
Update 2:
This is the complete PHP file with Your code with shutdown handler added. This works just fine and redirects to error_page.php. Change this to the page you want to redirect to.: