指定HOST訪問特定網址


平時測試過程中,經常會需要編輯HOST文件來訪問特定的服務器。實際上,這個過程也可以在代碼中完成。這個實現方式的根本,就是在HTTP請求的Header中,指定請求的HOST。

1、使用CURL

$ curl --silent -H "Host:house.baidu.com" "60.28.244.21/xxx/xxx/x.php"

2、使用PHP的CURL函數指定

   //httpHeader   設置的 http head 參數 數組形式 如 array('Host: [client.51.com](http://client.51.com/)')
   function comm_curl_request($url,$postString='',$httpHeader='')
   {
      $ch = curl_init();
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_POSTFIELDS,$postString);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
      curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
      if(!empty($httpHeader) && is_array($httpHeader))
      {
         curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
      }
      $data = curl_exec($ch);
      $info = curl_getinfo($ch);
      //var_dump($info);
      curl_close($ch);
      return $data;
   }

3、使用file_get_contents函數

   <?php

   $opts = array('http' => array( 'header' => 'Host: house.baidu.com',)); 
   $context = stream_context_create($opts); 
   $result = file_get_contents('[http://60.28.244.21/a.php](http://10.6.6.6/a.php)', false, $context); 

   echo $result;
 ?> 

參考資料:
1、CURL請求指定HOST的URL
2、不用設置HOST,訪問測試的HTTP接口


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM