如何避免file_get_contents错误:"无法解析主机名"

use*_*989 6 php

我成功地获取网站

file_get_contents("http://www.site.com");
Run Code Online (Sandbox Code Playgroud)

但是,如果网址不存在或无法访问,我会收到

Warning: file_get_contents(http://www.site.com) [function.file-get-contents]: 
failed to open stream: operation failed in /home/track/public_html/site.php 
on line 773
Run Code Online (Sandbox Code Playgroud)

是否可以echo "Site not reachable";代替错误?

hek*_*mgl 8

您可以将沉默运算符 @$php_errormsg:

if(@file_get_contents($url) === FALSE) {
    die($php_errormsg);
}
Run Code Online (Sandbox Code Playgroud)

@抑制错误消息的地方,消息文本将可用于输出$php_errormsg

但请注意,$php_errormsg默认情况下禁用.你必须打开track_errors.所以在代码的顶部添加:

ini_set('track_errors', 1);
Run Code Online (Sandbox Code Playgroud)

但是有一种方法不依赖于跟踪错误:

if(@file_get_contents($url) === FALSE) {
    $error = error_get_last();
    if(!$error) {
        die('An unknown error has occured');
    } else {
        die($error['message']);
    }
}
Run Code Online (Sandbox Code Playgroud)


sro*_*oes 6

我愿意触发异常而不是错误消息:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    // see http://php.net/manual/en/class.errorexception.php
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

set_error_handler("exception_error_handler");
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样捕获错误:

try {
    $content = file_get_contents($url);
} catch (ErrorException $ex) {
    echo 'Site not reachable (' . $ex->getMessage() . ')';
}
Run Code Online (Sandbox Code Playgroud)