简体   繁体   中英

Checking file handle type in PHP

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM