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

时间:2023-01-17 16:02:43

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 $site I get the following warning:

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

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

警告:file_get_contents(www.google.com)[功能。文件-获取-内容]:未能打开流:

I tried try and catch but it didn't work.

我试着去抓,但没有成功。

17 个解决方案

#1


402  

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

步骤1:检查返回代码:if($content === = FALSE){//句柄错误…}

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);

#2


108  

You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.

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

set_error_handler(
    create_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.

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

#3


51  

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/catch from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last to get the text of the last error, and file_get_contents returns false on failure, so a simple "if" can catch that.

我在上面的@enobrev尝试了try/catch之后发现了这一点,但是这允许更短的代码(在我看来,更容易读)。我们只需要使用error_get_last来获取最后一个错误的文本,而file_get_contents在失败时返回false,因此一个简单的“if”就可以捕获这个错误。

#4


30  

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……”的文件。

#5


15  

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

#6


12  

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

#7


11  

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
}

#8


6  

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

#9


3  

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

#10


1  

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

#11


1  

Since PHP 4 use error_reporting():

因为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;
}

#12


-1  

2018 solution:

2018的解决方案:

Here are tons of answers and nothing is working properly. If you suppress file_get_contents with an @ you will receive NULL and not false like some users claimed. So you have to do this:

这里有大量的答案,没有什么是正确的。如果你用@来抑制file_get_contents,你会收到NULL,而不是像一些用户声称的那样是假的。所以你必须这样做:

    $request = @file_get_contents = ...
    if (empty($request)) echo 'Connection error occured...';

#13


-2  

This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.

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

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

#14


-3  

Change the file php.ini

更改文件的php . ini

allow_url_fopen = On

allow_url_include = On

#15


-3  

You should also set the

您还应该设置

allow_url_use = On

allow_url_use =对

in your php.ini to stop receiving warnings.

在php。我要停止收到警告。

#16


-3  

You should use file_exists() function before to use file_get_contents(). With this way you'll avoid the php warning.

在使用file_get_contents()之前,应该使用file_exists()函数。这样可以避免php警告。

$file = "path/to/file";

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

#17


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

#1


402  

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

步骤1:检查返回代码:if($content === = FALSE){//句柄错误…}

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);

#2


108  

You can also set your error handler as an anonymous function that calls an Exception and use a try / catch on that exception.

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

set_error_handler(
    create_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.

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

#3


51  

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/catch from @enobrev above, but this allows for less lengthy (and IMO, more readable) code. We simply use error_get_last to get the text of the last error, and file_get_contents returns false on failure, so a simple "if" can catch that.

我在上面的@enobrev尝试了try/catch之后发现了这一点,但是这允许更短的代码(在我看来,更容易读)。我们只需要使用error_get_last来获取最后一个错误的文本,而file_get_contents在失败时返回false,因此一个简单的“if”就可以捕获这个错误。

#4


30  

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……”的文件。

#5


15  

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

#6


12  

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

#7


11  

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
}

#8


6  

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

#9


3  

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

#10


1  

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

#11


1  

Since PHP 4 use error_reporting():

因为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;
}

#12


-1  

2018 solution:

2018的解决方案:

Here are tons of answers and nothing is working properly. If you suppress file_get_contents with an @ you will receive NULL and not false like some users claimed. So you have to do this:

这里有大量的答案,没有什么是正确的。如果你用@来抑制file_get_contents,你会收到NULL,而不是像一些用户声称的那样是假的。所以你必须这样做:

    $request = @file_get_contents = ...
    if (empty($request)) echo 'Connection error occured...';

#13


-2  

This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.

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

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

#14


-3  

Change the file php.ini

更改文件的php . ini

allow_url_fopen = On

allow_url_include = On

#15


-3  

You should also set the

您还应该设置

allow_url_use = On

allow_url_use =对

in your php.ini to stop receiving warnings.

在php。我要停止收到警告。

#16


-3  

You should use file_exists() function before to use file_get_contents(). With this way you'll avoid the php warning.

在使用file_get_contents()之前,应该使用file_exists()函数。这样可以避免php警告。

$file = "path/to/file";

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

#17


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