2

Even I have specified the Content Length, I still receive the error:

Length Required


HTTP Error 411. The request must be chunked or have a content length.

This is my code

$curl = curl_init();
$data = array("Key" => "Value", "Key2" => "Value2");
$data = json_encode($data);
$length = strlen($data);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json;charset=utf-8", "Content-Length: $length"));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_HEADER, true);

$result = curl_exec($curl);

Any ideas whats wrong?

dwing265
  • 120
  • 1
  • 13

3 Answers3

3

Are you sure you need to be using the NTLM authentication option?

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);

I tested with this and it causes the content-type header as well as the JSON payload to be omitted from the request.

Try removing that line and see the request works.

drew010
  • 68,777
  • 11
  • 134
  • 162
  • Unfortunately yes. The application is protected by a Windows authentication. – dwing265 Jan 29 '16 at 12:08
  • 1
    In my test the `CURLAUTH_NTLM` option in conjunction with `CURLOPT_CUSTOMREQUEST` and a content-length header caused neither the content-length or the POST data to be sent. I was of course not testing with a server expecting NTLM so that may have caused the problem. Since NTLM is based on negotiation, you may need to issue one request with curl to auth, and then a subsequent PUT request to the API. Is their public documentation for the API you're working with? – drew010 Jan 29 '16 at 17:16
  • 1
    Unfortunately no public API, but issueing two request, the first just to authenticate, did the job! – dwing265 Feb 02 '16 at 14:15
2

You set Content-length to the length of $data, but you post $update_json instead $data

Gavriel
  • 18,880
  • 12
  • 68
  • 105
2

I had, sort of, the same problem and was breaking my brains on it for a couple of hours. Just remove the content-length from the header:

like this

curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json;charset=utf-8"))
mdgeus
  • 372
  • 2
  • 8
  • I was using php-curl-class using NLTM authentication and it was omitting my header"Content-Length". I spent my whole day trying to figure it out. It worked without any issue for the POST but for the PUT request, I had to set header "content-type" like it said to make it work. Not sure why its working for POST and not for PUT request though. Thank you. – prab May 10 '20 at 21:31