这是我正在使用的代码:
<?php
$changelog="https://raw.github.com/neurobin/oraji/release/ChangeLog";
$filec1=@file_get_contents($changelog);
if($filec1===false) {$filec1="something";}
echo $filec1
?>
它打印未找到而不是某些。但是当我在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正在发送文字"未找到"作为该不存在URL的内容(我不知道为什么)。但是我如何解决它(不使用文字字符串作为条件)?
这就是我最终所做的:
根据这个答案,我正在检查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时,此解决方案才有效。因此,这仍然不是一个好的解决方案
使用$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!';
}
还要注意,如果您取下@
,则会出现错误。
好吧,如果你访问链接,你会看到你得到错误。返回json的链接看起来像一个数组,即使它们在web中也是如此。
这正在按预期工作:
逻辑很简单:
无论是否重定向,如果URL有效,
$http_response_header
数组中的某个位置都会有一个200 OK
。
因此,我只是检查数组的所有元素,以查找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;
?>