您的位置:首页 > 其它

同一域名对应不同IP,访问指定主机文件内容的方法

2013-09-08 13:03 501 查看
PHP获取远程主机文件内容方法很多,例如:file_get_contents,fopen 等。

<?php
echo file_get_contents('http://demo.fdipzone.com/test.php');
?>
但如果同一域名对应了不同IP,例如 demo.fdipzone.com 对应3个IP192.168.100.101, 192.168.100.102, 192.168.100.103。

则不能使用file_get_contents获取 192.168.100.101的内容,因为会根据负载均衡原则分配到不同主机,因此并不能确定每次都是访问192.168.100.101这台主机。

如本地设置IP指定HOST的方法,但如果同一个程序中,需要先访问192.168.100.101,然后再访问192.168.100.102,则本地设置IP指定HOST的方法不行,因为不能将多个IP指定同一个域名。

因此,需要使用fsockopen方法去访问不同IP的主机,然后通过header设置host来访问。

使用fsockopen需要设置php.ini中的allow_url_fopen为 on。

<?php
/**
* @param  String $ip   主机ip
* @param  String $host 主机域名
* @param  int    $port 端口
* @param  String $url  访问的url
* @param  int    $timeout 超时时间
* @return String
*/
function remote_visit($ip, $host, $port, $url, $timeout){

$errno = '';
$errstr = '';

$fp = fsockopen($ip, $port, $errno, $errstr, $timeout);

if(!$fp){ // connect fail
return false;
}

$out = "GET ${url} HTTP/1.1\r\n";
$out .= "Host: ${host}\r\n";
$out .= "Connection: close\r\n\r\n";
fputs($fp, $out);

$response = '';

// 读取内容
while($row=fread($fp, 4096)){
$response .= $row;
}

fclose($fp);

$pos = strpos($response, "\r\n\r\n");
$response = substr($response, $pos+4);

return $response;
}

echo remote_visit('192.168.100.101', 'demo.fdipzone.com', 80, '/test.php', 90);
echo remote_visit('192.168.100.102', 'demo.fdipzone.com', 80, '/test.php', 90);
echo remote_visit('192.168.100.103', 'demo.fdipzone.com', 80, '/test.php', 90);

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐