如何处理 PHP 中 file_get_contents() 函数的警告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/272361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:09:08  来源:igfitidea点击:

How can I handle the warning of file_get_contents() function in PHP?

phpfunctionexception-handlingwarnings

提问by Waseem

I wrote a PHP code like this

我写了这样的 PHP 代码

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

But when I remove "http://" from $siteI get the following warning:

但是当我删除“http://”时,$site我收到以下警告:

Warning: file_get_contents(www.google.com) [function.file-get-contents]: failed to open stream:

警告:file_get_contents(www.google.com) [function.file-get-contents]:无法打开流:

I tried tryand catchbut it didn't work.

我试过了trycatch但没有用。

回答by Roel

Step 1: check the return code: if($content === FALSE) { // handle error here... }

第一步:检查返回码: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator(i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

第 2 步:通过在调用file_get_contents() 之前放置一个错误控制运算符(即@)来抑制警告: $content = @file_get_contents($site);

回答by enobrev

You can also set your error handleras an anonymous functionthat calls an Exceptionand use a try / catch on that exception.

您还可以将错误处理程序设置匿名函数,该函数调用Exception并对该异常使用 try / catch。

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();

Seems like a lot of code to catch one little error, but if you're using exceptions throughout your app, you would only need to do this once, way at the top (in an included config file, for instance), and it will convert all your errors to Exceptions throughout.

似乎有很多代码来捕获一个小错误,但是如果您在整个应用程序中使用异常,您只需要在顶部执行一次(例如在包含的配置文件中),它就会在整个过程中将所有错误转换为异常。

回答by Laurie

My favourite way to do this is fairly simple:

我最喜欢的方法很简单:

if (!$data = file_get_contents("http://www.google.com")) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}

I found this after experimenting with the try/catchfrom @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_lastto get the text of the last error, and file_get_contentsreturns false on failure, so a simple "if" can catch that.

我在对try/catch上面的@enobrev进行了实验后发现了这一点,但这可以减少冗长(和 IMO,更具可读性)的代码。我们只是error_get_last用来获取最后一个错误的文本,并file_get_contents在失败时返回 false,所以一个简单的“if”就可以捕捉到它。

回答by Greg

You can prepend an @: $content = @file_get_contents($site);

你可以在前面加上@: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

这将抑制任何警告 -谨慎使用!. 请参阅错误控制运算符

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

编辑:当您删除“http://”时,您不再查找网页,而是查找磁盘上名为“www.google .....”的文件

回答by Aram Kocharyan

One alternative is to suppress the error and also throw an exception which you can catch later. This is especially useful if there are multiple calls to file_get_contents() in your code, since you don't need to suppress and handle all of them manually. Instead, several calls can be made to this function in a single try/catch block.

一种替代方法是抑制错误并抛出一个您可以稍后捕获的异常。如果在您的代码中多次调用 file_get_contents(),这尤其有用,因为您不需要手动抑制和处理所有这些调用。相反,可以在单个 try/catch 块中对该函数进行多次调用。

// Returns the contents of a file
function file_contents($path) {
    $str = @file_get_contents($path);
    if ($str === FALSE) {
        throw new Exception("Cannot access '$path' to read contents.");
    } else {
        return $str;
    }
}

// Example
try {
    file_contents("a");
    file_contents("b");
    file_contents("c");
} catch (Exception $e) {
    // Deal with it.
    echo "Error: " , $e->getMessage();
}

回答by RafaSashi

function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}

回答by RafaSashi

Here's how I did it... No need for try-catch block... The best solution is always the simplest... Enjoy!

我是这样做的……不需要 try-catch 块……最好的解决方案总是最简单的……享受吧!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 

回答by Jrm

Here's how I handle that:

我是这样处理的:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}

回答by Jrm

The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones. http://www.php.net/set_error_handler

最好的办法是设置你自己的错误和异常处理程序,它们会做一些有用的事情,比如将它记录到文件中或通过电子邮件发送关键的。 http://www.php.net/set_error_handler

回答by ogie

You could use this script

你可以使用这个脚本

$url = @file_get_contents("http://www.itreb.info");
if ($url) {
    // if url is true execute this 
    echo $url;
} else {
    // if not exceute this 
    echo "connection error";
}