title: PHP CURL PUT keep receiving 422 error whiling using CURLOPT_POSTFIELDS
body: <p>I tried to write a script to let php do PUT request for me via <code>CURLOPT_CUSTOMREQUEST, 'PUT'</code> for me but I kept receiving 422 error (it means the data is formatted wrong and cannot be processed).</p>
  
  <p>First of, I tried direct sending out the PUT request in the terminal and postman, both works fine. The body of the request is a simple JSON format:</p>
  
  <pre><code>{"status":"online"}
  </code></pre>
  
  <p>Now, here are the code I tried:</p>
  
  <pre><code>  $ch = curl_init($url);
    curl_setopt_array($ch, array(        
      CURLOPT_HTTPHEADER =&gt; array( 'Authorization: "Panda is cute"' . "\r\n" . 'application/json; charset=utf-8' . "\r\n" . 'Content-Length: 19' . "\r\n" ),
      CURLOPT_RETURNTRANSFER =&gt; true,
      CURLOPT_CUSTOMREQUEST =&gt; 'PUT',
      CURLOPT_POST =&gt; false,
      CURLOPT_POSTFIELDS =&gt; http_build_query( array ("status" =&gt; "online") )
    ));
    $out = curl_exec($ch);
    curl_close($ch);
    echo $out;
  </code></pre>
  
  <p>I have tried a few modification of the code above.</p>
  
  <ol>
  <li>I tried <code>curl_setopt</code> everything instead of putting them all in <code>curl_setopt_array</code></li>
  <li>I tried setting <code>CURLOPT_POST</code> to true.</li>
  <li>I tried <code>CURLOPT_POSTFIELDS =&gt; json_encode( array ("status" =&gt; "online") )</code></li>
  <li>I tried <code>CURLOPT_POSTFIELDS =&gt; array ("status" =&gt; "online")</code></li>
  <li>I tried <code>CURLOPT_POSTFIELDS =&gt; '{"status":"online"}'</code></li>
  <li>I tried <code>CURLOPT_POSTFIELDS =&gt; 'http_build_query({"status":"online"})'</code></li>
  <li>I tried <code>CURLOPT_POSTFIELDS =&gt; 'http_build_query("status":"online")'</code></li>
  <li>I tried <code>json_encode</code> with the above two.</li>
  <li>I also tried all of the above with <code>curl_setopt</code>.</li>
  <li>I also tried to use <code>"</code> instead of my favorite <code>'</code> everywhere I could, like where I wrote <code>'PUT'</code></li>
  </ol>
  
  <p>Now, when I use non-custom PUT request and upload a file it does work, but this is posting a challenge because my production environment won't allow me to do <code>fopen()</code>.</p>
  
  <p>P.S. Thanks for the answer below, and I know why it didn't work now:</p>
  
  <p><code>CURLOPT_HTTPHEADER =&gt; array( 'Authorization: "Panda is cute"' . "\r\n" . 'application/json; charset=utf-8' . "\r\n" . 'Content-Length: 19' . "\r\n" )</code></p>
  
  <p>This line will put an additional <code>"\r\n"</code> at the end of the header (but without it php won't accept my original syntax and will post an error message, not rendering the header at all), making the content of my body <code>"\r\n"{"status":"online"}</code> instead.</p>