CURLOPT_POSTFIELDS in Curl for POST Requests
When using curl to perform a POST request and specifying the CURLOPT_POSTFIELDS option, it is crucial to consider the appropriate format. For instance, consider posting two fields, "first" and "last":
"first=John&last=Smith"
String Formatting
If sending a string as the POST data, it should be URL-encoded to ensure proper character encoding. The following code demonstrates this:
$data = urlencode("first=John&last=Smith");
Array Formatting
However, if the POST data is an array, it must follow the "key => value" format:
$data = [ 'first' => 'John', 'last' => 'Smith' ];
In this case, curl will automatically set the Content-Type header to "multipart/form-data".
Content-Type Header
Setting the Content-Type header explicitly is recommended for better compatibility. For example, to set it to "application/json":
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
Using http_build_query()
Alternatively, instead of manually building the query string, PHP's http_build_query() function can be used:
$query = http_build_query($data, '', '&'); curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
This function handles the URL-encoding and proper key=value formatting seamlessly.
The above is the detailed content of How to Properly Format CURLOPT_POSTFIELDS in cURL POST Requests?. For more information, please follow other related articles on the PHP Chinese website!