简体   繁体   中英

Error Handling in simple_html_dom.php

I am a beginner in PHP and I have a similar problem to that handled in:

Good error handling with file_get_contents

In simple_html_dom.php, there is a function called load_file, which is:

    function load_file() {
    $args = func_get_args();
    $this->load(call_user_func_array('file_get_contents', $args), true);
    }

In my PHP script, I use this function as:

$html->load_file($link);

When I try to load a broken link, I get a warning message on my output display like:

Warning: file_get_contents( http://www.yurowdesigns.com/UkraineSIG/test.asp ) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568

I would like to re-route this and similar error messages to an error.log file on my website rather than having it on my output display.

I naively tried to adapt the answer given in

Good error handling with file_get_contents

to my problem by adding the the function fget_contents() to my copy of simple_html_dom.php.

function fget_contents() {
$args = func_get_args();
// the @ can be removed if you lower error_reporting level
$contents = @call_user_func_array('file_get_contents', $args);

if ($contents === false) {
    throw new Exception('Failed to open ' . $file);
} else {
    return $contents;
}
}

And changed line 568 in load_file to read:

$this->load(call_user_func_array('fget_contents', $args), true);

But now, when I run my PHP script, I get a new error message:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'fget_contents' not found or invalid function name in /home/yurow/wwwroot/yurowdesigns.com/programs/simple_html_dom.php on line 568

Which means that simple_html_dom.php does not recognize the function 'fget_contents'

Where did I go wrong? How can I fix it?

Use the following code :

function load_file() {
    try{
       $args = func_get_args();
       $this->load(call_user_func_array('file_get_contents', $args), true);
    } catch(Exception e) {
      print_r(e);
    }
}

Here as you see it has try and catch block that will handle the errors.

To do that, in your PHP files, set them up to hide errors from being displayed. Use ini_set('display_errors','1'); and then log your errors using error_log or hopefully your default php.ini config already logs errors using the error_log string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM