سؤال

Below is an example without CURLOPT_HTTPHEADER, and it works fine.

<?php
$URL = "http://someurl.info"; 
$data = 'x_test_request=0&x_version=3.1&x_delim_data=true&x_relay_response=false';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 1800);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
$response = curl_exec($ch);

?>

Does Curl auto-detect the type of data we Post, and auto-count the string length? Or should we always specify Both?

Or does it largely depend on the destination's rules and expectations?

To be safe, I usually add the header info like this:

<?php
$contentlen = strlen(trim($data));
$headersARR = array(
        "Content-type: application/x-www-form-urlencoded",
                "Content-length: ".$contentlen,
        ); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headersARR);
?>

I read http://us1.php.net/curl_setopt, but haven't noticed any details on defaulted content-type parameters.

هل كانت مفيدة؟

المحلول

If you do not specify anything about Content-type but use the CURLOPT_POSTFIELDS then the header is always Content-type: application/x-www-form-urlencoded as default. Also it sets the Content-length: automatically.

For this reason, when we post JSON content through the POST we need to override the content-type through HTTPHEADER option. It is similar to XML or any other specific type of content.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top