当我们要测试的接口服务器比较多的时候,更改hosts指向很麻烦,通过socket我们可以在程序中绑定接口域的ip,增加测试的灵活性,代码如下
<?php
/**
* 访问域名url时绑定ip地址
*
* @author tonywang(wtmmac(@)gmail.com)
* @param string $url 目标url
* @param string $ip_address 绑定IP地址
* @param bool $return_header 是否返回头信息
*
* @return string 返回GET到的信息
*/
function url_get_contents($url, $ip_address = null, $return_header = false) {
$url = parse_url($url);
if (!isset($url['port'])) {
if ($url['scheme'] == 'http'){
$url['port'] = 80;
} else if ($url['scheme'] == 'https'){
$url['port'] = 443;
}
}
$url['query'] = isset($url['query'])?$url['query']:'';
$url['protocol'] = $url['scheme'].'://';
$eol="\r\n";
$headers = 'GET '.$url['protocol'].$url['host'].$url['path'].' HTTP/1.0'.$eol.
'Host: '.$url['host'].$eol.
'Content-Length: '.strlen($url['query']).$eol.
$eol.$url['query'];
$fp = fsockopen($ip_address ? $ip_address : $url['host'], $url['port'], $errno, $errstr, 5);
if ($fp) {
fputs($fp, $headers);
$result = $headers;
while(!feof($fp)){
$result .= fgets($fp, 128);
}
fclose($fp);
if (!$return_header) {
$result = preg_replace("/^.*\r\n\r\n/s",'',$result);
}
return $result;
}
}
echo url_get_contents('http://www.ibaofeng.com', '127.0.0.1');