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
Release: 2024-12-08 21:39:17
Original
541 people have browsed it

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';
Copy after login

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'];
Copy after login

Helper Function:

To simplify the process for arrays, you can use the http_build_query() function:

$query = http_build_query($data, '', '&');
$data = $query;
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template