简体   繁体   English

在PHP中检查文件句柄类型

[英]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. 我正在使用fopen从URL打开提要(.txt文件),但有时找不到提要。 I would like fopen to return FALSE when this happens, so I can handle the error. 我希望fopen在发生这种情况时返回FALSE,因此我可以处理该错误。 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. 但是,如果在目标URL上未找到供稿,则会将我重定向到网站上的另一个页面,通知我未找到指定的文件。 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. 结果是,我的$ handle指向错误的文件,而fopen返回TRUE(因为它找到了-某些东西-尽管是错误的东西),从而破坏了我对错误处理的尝试。

How can I verify that fopen has got the right file? 如何验证fopen的文件正确? 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: 您可以使http包装器忽略重定向,如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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