【发布时间】:2015-12-25 13:16:26
【问题描述】:
这是我正在使用的代码:
<?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
注意:我在远程服务器上执行此操作。
编辑:
无论如何,我注意到(在浏览器中访问该 URL)Github 正在发送文字“未找到”作为该不存在 URL 的内容(我不知道为什么)。但是我该如何解决它(不使用文字字符串作为条件)?
这就是我最终做的:
根据 this answer,我正在检查 HTTP 标头响应并将 200 定位为成功代码,否则将失败(以及真/假检查)。
<?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 重定向,那么这将不起作用。例如,如果上面的链接确实存在,它将不起作用,即它将返回“某物”而不是重定向页面中的实际内容。因为raw.github.com被重定向到raw.githubusercontent.com
此解决方案仅在我使用没有重定向的实际 URL 时才有效。 所以这仍然不是一个好的解决方案。
【问题讨论】:
-
给自己的 url 返回字符串
not found,这就是它起作用的原因。 -
字符串“未找到”看起来像页面的主体。您确定 $changelog 是正确的 URL 并且可以从远程访问吗?
-
以上两位评论员都说对了。
-
如果 github 没有返回“200 OK”状态,你可以使用它。为此,请使用 CURL 或 Guzzle 等 HTTP 客户端库。