开发者

file_get_contents - How to handle a URL not being there?

If a UR开发者_高级运维L is not accessible, then I need to handle it. From my tests, file_get_contents doesn't seem to return false when a page returns 404 or 502.

Am I missing a trick here?


Don't use file_get_contents to access a URL. It's much slower than curl, and it isn't hardly any easier. Not to mention, handling errors in curl is a lot more graceful:

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


You might want to take a look at the $http_response_header which changes after each request made via your file_get_contents() call

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


It returns false for me... php 5.3.5...

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


You can use get_headers(); before and checking if in the response there is 200 OK.


You could use file_exists, which returns true or false, depending on whether the file exists.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜