Home > Backend Development > PHP Tutorial > How to Properly Format CURLOPT_POSTFIELDS in cURL POST Requests?

How to Properly Format CURLOPT_POSTFIELDS in cURL POST Requests?

Linda Hamilton
Release: 2024-12-25 07:08:09
Original
902 people have browsed it

How to Properly Format CURLOPT_POSTFIELDS in cURL POST Requests?

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

Array Formatting

However, if the POST data is an array, it must follow the "key => value" format:

$data = [
    'first' => 'John',
    'last' => 'Smith'
];
Copy after login

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

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

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!

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