2012-04-29 161 views
3

我在使用PHP中的cURL腳本發送POST請求時遇到問題。cURL POST:400無效的內容長度

我想爲我自己的個人使用做一個代理,它將通過服務器獲取網頁並在本地顯示給我。

該網址發現,像這樣:http://fetch.example.com/http://theurl.com/

當我發佈在頁面上的表單,它會去表單的ACTION(前面帶有獲取URL)。我正在嘗試使用下面的代碼來處理這個POST請求,但是任何我POST的東西總是會帶來一個400錯誤的請求錯誤。

$chpg = curl_init(); 
curl_setopt($chpg, CURLOPT_URL, $_URL); 
curl_setopt($chpg, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($chpg, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($chpg, CURLOPT_COOKIESESSION, true); 
curl_setopt($chpg, CURLOPT_COOKIEJAR, "cookies/$_COOKIE_FILE.$_DOMAIN.txt"); 
curl_setopt($chpg, CURLOPT_COOKIEFILE, "cookies/$_COOKIE_FILE.$_DOMAIN.txt"); 
if($_POST) { 
    $fields = array(); 
    foreach($_POST as $col => $val) { 
     $fields[$col] = urlencode($val); 
    } 
    print_r($fields); 
    curl_setopt($chpg, CURLOPT_POST, count($fields)); 
    curl_setopt($chpg, CURLOPT_POSTDATA, $fields); 
} 

回答

3

你有一對夫婦的問題有:

  1. CURLOPT_POSTDATA應該是CURLOPT_POSTFIELDS

  2. 你要發送的$fieldsPHP數組作爲 CURLOPT_POSTFIELDS。這實際上需要是 格式name1=value1&name2=value2&...中的字符串。

    要解決這些問題,修改你的PHP代碼如下:

    if($_POST) { 
        $fields_str = http_build_query($_POST); 
    
        curl_setopt($chpg, CURLOPT_POST, count($_POST)); 
        curl_setopt($chpg, CURLOPT_POSTFIELDS, $fields_str); 
    } 
    

    由於Lawrence Cherone指出的那樣,你可以溝foreach循環和使用http_build_query代替。

+0

取而代之的是foreach循環,你可以只是做的'$ fields_str = http_build_query($ _ POST)'http://php.net/manual/en /function.http-build-query.php – 2012-04-29 03:05:38

+0

@LawrenceCherone:哈,太棒了。我沒有意識到存在!每天學些新東西。 :) – Xenon 2012-04-29 03:07:52

+0

我需要在查詢中使用urlencode嗎?看來我無法通過此項目登錄到Hotmail - 它說我的電子郵件和傳遞是正確的,但我看到了查詢並且顯示正常。 – Anonymous 2012-04-29 03:21:59

2

嘗試使用這個http_build_query &固定CURLOPT_POSTFIELDS

$chpg = curl_init(); 
curl_setopt($chpg, CURLOPT_URL, $_URL); 
curl_setopt($chpg, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($chpg, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($chpg, CURLOPT_COOKIESESSION, true); 
curl_setopt($chpg, CURLOPT_COOKIEJAR, "cookies/$_COOKIE_FILE.$_DOMAIN.txt"); 
curl_setopt($chpg, CURLOPT_COOKIEFILE, "cookies/$_COOKIE_FILE.$_DOMAIN.txt"); 
if($_POST) { 
    curl_setopt($chpg, CURLOPT_POST, count($_POST)); 
    curl_setopt($chpg, CURLOPT_POSTFIELDS, http_build_query($_POST)); 
}