cURL POST: 400 Invalid content length

curl, php, post

Solution

You have a couple of problems there:

`CURLOPT_POSTDATA` should be `CURLOPT_POSTFIELDS`.

You're sending the `$fields` PHP array as the `CURLOPT_POSTFIELDS`. This actually needs to be a string in the format `name1=value1&name2=value2&...`.

To fix these problems, modify your PHP code as follows:

if($_POST) {
    $fields_str = http_build_query($_POST);

    curl_setopt($chpg, CURLOPT_POST, count($_POST));
    curl_setopt($chpg, CURLOPT_POSTFIELDS, $fields_str);
}

As Lawrence Cherone pointed out, you can ditch the `foreach` loop and use `http_build_query` instead.

Problem

I am having issues sending POST requests with my cURL script in PHP. I am trying to make a proxy, essentially, for my own personal use, that will get the web page via the server and display it to me locally. The URL is found like so: http://fetch.example.com/http://theurl.com/ When I post in a form on that page, it will go to the form's ACTION (with the fetch URL in front). I am trying to make it process this POST request using the code below, but anything I POST always brings a 400 Bad Request error. ``` $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); } ```

Original source