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


    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
    ";
        $out .= "Host: ${host}
    ";
        $out .= "Connection: close
    
    ";
        fputs($fp, $out);
    
        $response = '';
    
        // 读取内容
        while($row=fread($fp, 4096)){
            $response .= $row;
        }
    
        fclose($fp);
    
        $pos = strpos($response, "
    
    ");
        $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);
    
    ?>

  • 相关阅读:
    PHP数组的几个操作,求并集,交集,差集,数组与字符串的相互转换及数组去重
    文件系统添加链接
    HTML中插入视频
    magento模块的建立
    数组函数
    字符串函数
    阿里服务器用户的添加
    ViewChild
    GitHub 图片加载不出来怎么办
    常用正则表达式
  • 原文地址:https://www.cnblogs.com/fdipzone/p/3715090.html
Copyright © 2020-2023  润新知