file_get_contents() returns 文字 'Not Found' 而不是布尔值

file_get_contents() returns literal 'Not Found' instead of boolean

这是我使用的代码:

<?php 
$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
$filec1=@file_get_contents($changelog);

if($filec1===false) {$filec1="something";}

echo $filec1
?>

它打印 Not Found 而不是 something。但是当我像这样向 if 语句添加另一个条件时:

if($filec1===false||$filec1=="Not Found") {$filec1="something";}

然后它按预期工作。

这里出了什么问题?

PHP版本是5.4。 php -v 输出:

PHP 5.4.45 (cli) (built: Oct 29 2015 09:16:10) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with the ionCube PHP Loader v4.7.5, Copyright (c) 2002-2014, by ionCube Ltd., and
    with Zend Guard Loader v3.3, Copyright (c) 1998-2013, by Zend Technologies
    with Suhosin v0.9.36, Copyright (c) 2007-2014, by SektionEins GmbH

N.B: 我在远程服务器上做这个。


编辑:

无论如何,我注意到(在浏览器中转到 URL)Github 正在发送文字 'Not Found' 作为 non-existing URL 的内容(我不知道为什么)。但是我该如何解决它(不使用文字字符串作为条件)?

这就是我最后做的:

根据 this answer,我正在检查 HTTP header 响应并将 200 作为成功代码,否则会失败(以及 true/false 检查) .

<?php 
function fileGetContents($file){
    $filec1=@file_get_contents($file);
    if($filec1===false || !strpos($http_response_header[0], "200")) 
        {$filec1="something";}
    return $filec1;
}

$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
$filec1=fileGetContents($changelog);

echo $filec1;
?>

注:

如果使用 301/302 重定向,则这将不起作用。例如,如果上面的 link 确实存在,它就不会起作用,即它会 return 'something' 而不是重定向页面中的实际内容。因为 raw.github.com 被重定向到 raw.githubusercontent.com

此解决方案仅在我使用没有重定向的实际 URL 时有效。 所以这仍然不是一个好的解决方案。

使用$http_response_header:

$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
$filec1=@file_get_contents($changelog);

if($filec1===false || $http_response_header[0] == 'HTTP/1.1 404 Not Found') {$filec1="something";}

file_get_contents 置于条件句中。

$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
if($filec1 = @file_get_contents($changelog)) {
    echo 'Got it';
} else {
    echo 'NOOOOOoooo!';
}

另请注意,如果您取下 @,则会出现错误。

这按预期工作:

逻辑很简单:

Redirect or not, there will be a 200 OK somewhere in $http_response_header array if the URL is valid.

因此,我只是检查数组的所有元素以查找 200 OK 消息。

<?php 
function is200OK($arr){
    foreach($arr as $str){
        if(strpos($str, " 200 OK")) {return true;}
    }
    return false;
}

function fileGetContents($file){
    $filec1=@file_get_contents($file);
    if($filec1===false || !is200OK($http_response_header)) {$filec1="something";}
    //print_r($http_response_header);
    return $filec1;
}

$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
$filec1=fileGetContents($changelog);

echo $filec1;
?>

好吧,如果您访问 link,您会看到该错误。 returns json 的链接看起来像一个数组,即使它们在网络中也是如此。