2012-01-07 61 views
2

使用fsockopen這個原始HTTP調用有什麼問題?使用fsockopen POST到GET查詢URL

POST /api/?action=report HTTP/1.1 
Host: www.webhosting-performance.com 
Content-Type: application/x-www-form-urlencoded 
Conent-Length: 9 
Connection: close 

test=test 

遠程腳本顯示var_dump($ _ POST)爲空。

的我的PHP代碼片段看起來是這樣的:

if (ini_get('allow_url_fopen') > 0) { 

    $parts = parse_url($url); 
    $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30); 

    if (!$fp) throw new Exception("Problem with $url, $errstr"); 

    $post_string = $post_fields ? http_build_query($post_fields) : ''; 

    $out = ($post_string ? "POST " : "GET ") . $parts['path'] . ((isset($parts['query'])) ? "?" . $parts['query'] : false) ." HTTP/1.1\r\n" 
     . "Host: ". $parts['host'] ."\r\n" 
     . ($post_string ? "Content-Type: application/x-www-form-urlencoded\r\n" : false) 
     . "Conent-Length: ". strlen($post_string) ."\r\n" 
     . "Connection: close\r\n" 
     . "\r\n" . $post_string; 

    fwrite($fp, $out); 

    // ... 

} else { 
    // use curl 
} 

回答

2

你基本上只是有一個錯字:

Conent-Length: 9 

Content-Length:

真正的問題是缺少t(不要詆譭你自己構建某種東西的努力),爲什麼不使用cURLPEARs HTTP Request類?

+0

多年的經驗,以及如此嘮叨的小錯字。我坐了幾個小時試圖解決這個問題。錯誤地不斷複製該錯字。非常感謝您爲我節省了一小時的時間;)乾杯 – tim 2012-01-07 03:15:58

+0

至於您的其他問題。我試圖儘可能本地化,因此客戶平臺不支持incase擴展。至於這個函數,如果allow_url_fopen被禁用,它支持curl。我也可以加PEARs。 – tim 2012-01-07 03:45:17