`
wtm_mac
  • 浏览: 89092 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

php请求域名的url时绑定ip

阅读更多
当我们要测试的接口服务器比较多的时候,更改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');
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics