CURL POST: 400 Invalid content length

I am having problems sending POST requests with my cURL script in PHP.

I am trying to make a proxy server, in fact, for personal use, which will receive a web page through the server and display it to me locally.

The URL is found as follows: http://fetch.example.com/http://theurl.com/

When I submit the form on this page, it will go to the ACTION form (with the extraction URL in front). I am trying to get it to process this POST request using the code below, but everything I get POST always results in 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);
}
+3
source share
2 answers

You have a couple of problems:

  • CURLOPT_POSTDATAshould be CURLOPT_POSTFIELDS.

  • $fields PHP 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);
    }
    

    , foreach http_build_query.

+3

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));
}
+2

All Articles