Home >Backend Development >PHP Tutorial >How to Properly Use CURLOPT_POSTFIELDS with cURL for String and Array Data?
Using CURLOPT_POSTFIELDS with cURL
When using cURL with CURLOPT_POSTFIELDS to send data via POST, it is important to consider the appropriate data format.
For String Data:
If you are sending a string, you should urlencode it to ensure proper formatting. For example:
$data = 'first=John&last=Smith';
For Arrays:
When posting an array, key-value pairs are required. The Content-Type header is automatically set to "multipart/form-data" for arrays.
$data = ['first' => 'John', 'last' => 'Smith'];
Helper Function:
To simplify the process for arrays, you can use the http_build_query() function:
$query = http_build_query($data, '', '&'); $data = $query;
Example:
The following example demonstrates a complete code snippet using CURLOPT_POSTFIELDS:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $reply = curl_exec($ch); curl_close($ch);
The above is the detailed content of How to Properly Use CURLOPT_POSTFIELDS with cURL for String and Array Data?. For more information, please follow other related articles on the PHP Chinese website!