php 傳送get到別的URL並取得回應內容 使用fsockopen

這篇有提到傳送post的用法

另外說到如果只是要傳送get就可以直接使用fopen或是file_get_contents函式直接取得網頁內容
BUT!!!
這兩天遇到了一個問題
如果因為安全性的關係
要把php.ini中的allow_url_fopen關起來(也就是off)
那就不能使用前述的函式來取得網頁內容
所以只好找另外的方法
也就是使用fsockopen模擬傳送~
(鏘鏘鏘~)

以下是php部份

function SendGET($_url){
  $url = parse_url($_url);
  $contents = '';
  $url_port = $url['port']==''?80:$url['port'];
  $fp = fsockopen($url['host'],$url_port);
  if($fp){
    $_request = $url['path'].($url['query']==''?'':'?'.$url['query']).($url['fragment']==''?'':'#'.$url['fragment']);
    fputs($fp,'GET '.(($_request=='')?'/':$_request)." HTTP/1.0\r\n");
    fputs($fp,"Host: ".$url['host']."\n");
    fputs($fp,"Content-type: application/x-www-form-urlencoded\n");
    fputs($fp,"Connection: close\n\n");
    $line = fgets($fp,1024);
    if(!eregi("^HTTP/1\.. 200", $line)) return;
    else{
      $results = '';
      $contents = '';
      $inheader = 1;
      while(!feof($fp)){
        $line = fgets($fp,2048);
        if($inheader&&($line == "\n" || $line == "\r\n")){
          $inheader = 0;
        }elseif(!$inheader){
          $contents .= $line;
        }
      }
      fclose($fp);
    }
  }
  return $contents;
}
//使用方式很簡單
$url = 'http://someone.com:80/index.php?mode=go&id=hsin#top';
//把網址填入參數即可
$_result = SendGET($url);
//回傳的值就是內容
print_r($_result);

參考資訊:http://www.maorr.com/read.php/447.htm

本篇發表於 php 並標籤為 。將永久鏈結加入書籤。

php 傳送get到別的URL並取得回應內容 使用fsockopen 有 3 則回應

  1. Chan 說道:

    So if I want to the URL be leathy.com/index.php?contact , how should I do?

  2. Chan 說道:

    Is that I just make the$URL link be leathy.com/index.php?contact ?

  3. hsin 說道:

    @Chan
    Replace the value of variable $_request in line 06. with the original url (leathy.com/index.php?contact)
    That will be correct.

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*

您可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>