Home >Backend Development >PHP Tutorial >How to Properly Use CURLOPT_POSTFIELDS with cURL for String and Array Data?

How to Properly Use CURLOPT_POSTFIELDS with cURL for String and Array Data?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 21:39:17536browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn