开发者

Checking file handle type in PHP

开发者 https://www.devze.com 2023-03-26 08:57 出处:网络
I\'m using fopen to open a feed (.txt file) from a URL but sometimes the feed isn\'t found. I would like fopen to return FALSE when this happens, so I can handle the error. However, when the feed isn\

I'm using fopen to open a feed (.txt file) from a URL but sometimes the feed isn't found. I would like fopen to return FALSE when this happens, so I can handle the error. However, when the feed isn't found on the target URL, I'm being redirected to another page on the site, informing me that the specified file wasn't 开发者_高级运维found. The result being, my $handle refers to the wrong file, and fopen returns TRUE (because it has found -something- albeit the wrong thing), thus sabotaging my attempt at error handling.

How can I verify that fopen has got the right file? Thanks.

if ($handle = fopen($feed, "r")) {
   //fopen returned true, do stuff
} else {
   //fopen returned false, quit
   die("Fail.");
}


You can get the http wrapper to ignore redirects as follows:

$opts = array(
    'http' => array('method' => 'GET',
                    'max_redirects' => '0')
);

$context = stream_context_create($opts);
$handle = fopen($feed, 'r', false, $context);
0

精彩评论

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

关注公众号