2012-04-01 40 views
2

我想送與fsock, 後變數,但是當我嘗試這個辦法:fsock:找不到插座運輸「HTTP」

$post_arr = array ("a" => "b"); 
    $addr = 'http://1.2.3.4/confirmation.html'; 

    $fp = fsockopen($addr, 80, $errno, $errstr, 30); 
    if (!$fp) { 
     echo "$errstr ($errno)<br />\n"; 
    } else { 

     $req = ''; 
     foreach ($post_arr as $key => $value) { 
      $value = urlencode(stripslashes($value)); 
      $req .= "&" . $key . "=" . $value; 
     } 


     $header = "POST /cgi-bin/webscr HTTP/1.0\r\n"; 
     $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
     $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; 
     fwrite($fp, $header); 
     while (!feof($fp)) { 
      echo fgets($fp, 128); 
     } 
     fclose($fp); 
    } 

我得到「無法找到插座運輸‘HTTP’」 , 有什麼想法爲什麼?

+0

這個小程序庫可以幫助你編寫更簡單的HTTP請求:https://github.com/jamm/HTTP – 2012-04-01 15:11:01

+2

你應該省略'http://'部分,默認情況下'tcp:'transport是用過的。 – 2012-04-01 15:30:51

回答

7

fsockopen()打開一個插座。套接字不知道關於Layer5 +協議的任何信息,例如HTTP。

$fp = fsockopen('1.2.3.4', 80, $errno, $errstr, 30); 

要請求特定路徑,在請求發送:GET /confirmation.html
要指定域,在Host頭髮送:Host: 1.2.3.4


你可能要考慮使用curl延期。在PHP中手動構建HTTP請求通常沒有什麼好的理由。

+0

這真的取決於。捲曲可能是可取的,但並不總是安裝。我已經在我編寫和發佈的軟件包中遇到過這個問題。捲曲還增加了一些額外的開銷。 – Peter 2012-04-01 16:24:23