我正在使用PHP file_get_contents来读取文本文件数据。
假设我有两个IP地址,一个在线,一个离线:
192.168.180.181 - Online
192.168.180.182 - Offline和PHP
$fileAccept = file_get_contents("\\\\192.168.180.181\\Reports\\".$dModel['MODEL_NAME'].$source."\\Accept\\Accept_".$dDtl['MODEL_CODE']."_".$dateCode."_".$dDtl['TS_CODE'].".txt");因为我们知道IP地址192.168.180.182是离线的,所以我试着运行代码。并导致页面始终加载。
我的问题是,我如何防止它,也许首先需要检查IP是否活着,如果活着,那么可以继续下一步。
可能是这样的:
if(IP IS OFFLINE)
{
echo "do not do anything";
}
else
{
echo "do something";
}发布于 2018-12-21 10:20:53
你可以试试这样的东西
$scc = stream_context_create(array('http'=>
array(
'timeout' => 120, //120 seconds
)
));
$url = "http://192.168.180.181/....";
$handle = file_get_contents('$url, false, $scc);您可以创建两个句柄并使用if语句检查是否可以,当然,您可以根据需要更改超时
更新:如果你在本地访问文件,你可以检查这个stream_set_timeout()函数,documentation is here
发布于 2018-12-21 11:42:18
此方案基于pinging您需要检查的IP
class IPChecker{
public static function isIPOnline($ip){
switch (SELF::currentOS()){
case "windows":
$arg = "n";
break;
case "linux":
$arg = "c";
break;
default: throw new \Exception('unknown OS');
}
$result = "";
$output = [];
// to debug errors add 2>&1 to the command to fill $output
// https://stackoverflow.com/questions/16665041/php-why-isnt-exec-returning-output
exec("ping -$arg 2 $ip " , $output, $result);
// if 0 then the there is no errors like "Destination Host Unreachable"
if ($result === 0) return true;
return false;
}
public static function currentOS(){
if(strpos(strtolower(PHP_OS), "win") !== false) return 'windows';
elseif (strpos(strtolower(PHP_OS), "linux") !== false) return 'linux';
//TODO: extend other OSs here
else return 'unknown';
}
}使用示例
var_dump( IPChecker::isIPOnline("192.168.180.181") );// should outputs bool(true)
var_dump( IPChecker::isIPOnline("192.168.180.182") );// should outputs bool(false) https://stackoverflow.com/questions/53878328
复制相似问题