file_get_contents - 如何处理不存在的URL?

时间:2011-02-22 22:51:04

标签: php

如果无法访问URL,那么我需要处理它。从我的测试中,当页面返回404或502时,file_get_contents似乎没有返回false。

我在这里错过了一招吗?

5 个答案:

答案 0 :(得分:4)

请勿使用file_get_contents来访问网址。它比卷曲慢得多,而且几乎不容易。更不用说,处理curl中的错误更加优雅:

$ch = curl_init('http://example.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

if ($errmsg = curl_error($ch)) {
  echo $errmsg;
} else {
  // hooray
}

答案 1 :(得分:3)

您可能需要查看通过$http_response_header来电发出的每次请求后发生变化的file_get_contents()

http://www.php.net/manual/en/reserved.variables.httpresponseheader.php

答案 2 :(得分:1)

它为我返回false ... php 5.3.5 ...

<?php echo file_get_contents("http://www.google.com/xyzabc")===false ? "Returned False" : "Did not return False"; ?>

答案 3 :(得分:1)

您可以先使用get_headers();并检查回复中是否有200 OK

答案 4 :(得分:0)

您可以使用file_exists,它返回true或false,具体取决于文件是否存在。

<?php
$path='path/to/file.txt';
if (file_exists($path))
  {
  $contents=file_get_contents($path);
  }
// Process contents.
?>