php file_get_contents函數代理擷取遠程頁面的代碼

來源:互聯網
上載者:User
  1. $url = "http://bbs.it-home.org/";
  2. $ctx = stream_context_create(array(
  3. 'http' => array('timeout' => 5,
  4. 'proxy' => 'tcp://60.175.203.243:8080',
  5. 'request_fulluri' => True,)
  6. )
  7. );
  8. $result = file_get_contents($url, False, $ctx);
  9. echo $result;
  10. ?>
複製代碼

2、curl 代理的方法:

  1. function postPage($url)
  2. {
  3. $response = "";
  4. $rd=rand(1,4);
  5. $proxy='http://212.33.27.253:808';
  6. if($rd==2) $proxy='http://212.88.16.56:8088';
  7. if($rd==3) $proxy='http://202.98.123.126:8080';
  8. if($rd==4) $proxy='http://59.14.97.38:8080';
  9. if($url != "") {
  10. $ch = curl_init($url);
  11. curl_setopt($ch, CURLOPT_HEADER, 0);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  13. curl_setopt($ch, CURLOPT_PROXY, $proxy);
  14. $response = curl_exec($ch);
  15. if(curl_errno($ch)) $response = "";
  16. curl_close($ch);
  17. }
  18. return $response;
  19. }
複製代碼

附:使用php file_get_contents解決ajax垮域的問題

在ajax運用中,有時會垮域調用檔案,而瀏覽器為了安全會預設給這種操作提出警告,甚至直接阻止。如果是IE會彈出一個警告視窗,詢問你是否繼續操作,只有你同意了IE才會調用垮域的檔案。而其它瀏覽器,如Firefox、Opera預設設定下則會直接提示錯誤,阻止調用外域檔案。這會給使用者不好的操作體驗,如果想通過使用者修改瀏覽器的安全設定來解決這個問題是不現實的,最好是在伺服器端解決。

在伺服器端可以使用一個同域的檔案做為代理檔案,這個代理檔案將獲得外域檔案的內容,然後再傳遞給ajax。這樣ajax就不是調用外域檔案,而是調用同域的這個代理檔案,安全問題也就解決了。

如果伺服器端支援PHP,可以使用file_get_contents函數,詳細用法可參考:http://www.w3school.com.cn/php/func_filesystem_file_get_contents.asp例子:

  1. $serverAddress = 'http://s.jbxue.com';
  2. //獲得外域檔案內容
  3. $randomNumber = file_get_contents($serverAddress);
  4. //輸出內容
  5. echo $randomNumber;
  6. ?>
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.