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

时间:2008-11-07 15:10:53

标签: php function exception-handling warnings

我写了一个像这样的PHP代码

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

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

  

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

我尝试了trycatch,但它没有用。

20 个答案:

答案 0 :(得分:458)

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

第2步:通过在 file_get_contents()的调用前加error control operator(即@)来取消警告: $content = @file_get_contents($site);

答案 1 :(得分:128)

您也可以set your error handler作为anonymous function调用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();

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

答案 2 :(得分:59)

我最喜欢这样做的方法很简单:

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";
}

我在使用上面的@enobrev中的try/catch进行了实验后发现了这一点,但这样可以减少冗长(和IMO,更易读)的代码。我们只需使用error_get_last来获取上一个错误的文本,file_get_contents在失败时返回false,因此一个简单的“if”可以捕获它。

答案 3 :(得分:31)

您可以添加@: $content = @file_get_contents($site);

这会压制任何警告 - 谨慎使用!。见Error Control Operators

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

答案 4 :(得分:18)

另一种方法是抑制错误并抛出一个稍后可以捕获的异常。如果在代码中多次调用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();
}

答案 5 :(得分:13)

这就是我如何做到的......不需要尝试捕捉......最好的解决方案总是最简单的......享受!

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

答案 6 :(得分:13)

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
}

答案 7 :(得分:6)

以下是我处理的方法:

$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();
}

答案 8 :(得分:3)

最好的方法是设置自己的错误和异常处理程序,这些处理程序将执行一些有用的操作,例如将其记录在文件中或通过电子邮件发送重要文件。 http://www.php.net/set_error_handler

答案 9 :(得分:1)

由于PHP 4使用error_reporting()

$site="http://www.google.com";
$old_error_reporting = error_reporting(E_ALL ^ E_WARNING);
$content = file_get_content($site);
error_reporting($old_error_reporting);
if ($content === FALSE) {
    echo "Error getting '$site'";
} else {
    echo $content;
}

答案 10 :(得分:1)

if (!file_get_contents($data)) {
  exit('<h1>ERROR MESSAGE</h1>');
} else {
      return file_get_contents($data);
}

答案 11 :(得分:1)

最简单的方法是在file_get_contents之前加一个@, 一世。 e。:

$content = @file_get_contents($site); 

答案 12 :(得分:1)

您可以使用此脚本

$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";
}

答案 13 :(得分:0)

类似这样的东西:

public function get($curl,$options){
    $context = stream_context_create($options);
    $file = @file_get_contents($curl, false, $context);
    $str1=$str2=$status=null;
    sscanf($http_response_header[0] ,'%s %d %s', $str1,$status, $str2);
    if($status==200)
        return $file        
    else 
        throw new \Exception($http_response_header[0]);
}

答案 14 :(得分:0)

从 cPanel 或 WHM 启用 allow_url_fopen 然后尝试希望它会修复

答案 15 :(得分:-2)

这将尝试获取数据,如果它不起作用,它将捕获错误并允许您在catch中执行任何操作。

try {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}

答案 16 :(得分:-2)

您之前应该使用file_exists()函数来使用file_get_contents()。 通过这种方式,您将避免php警告。

$file = "path/to/file";

if(file_exists($file)){
  $content = file_get_contents($file);
}

答案 17 :(得分:-3)

您还应该设置

allow_url_use = On 

php.ini中停止接收警告。

答案 18 :(得分:-3)

try {
   $site="http://www.google.com";
   $content = file_get_content($site);
   echo $content;
} catch (ErrorException $e) {
    // fix the url

}

set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine ) 
{
    throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});

答案 19 :(得分:-3)

更改文件php.ini

allow_url_fopen = On

allow_url_include = On