curl POST format for CURLOPT_POSTFIELDS

Ken picture Ken · Mar 7, 2011 · Viewed 262.1k times · Source

When I use curl via POST and set CURLOPT_POSTFIELD do I have to urlencode or any special format?

for example: If I want to post 2 fields, first and last:

first=John&last=Smith

what is the exact code/format that should be used with curl?

$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);

Answer

kodeart picture kodeart · Mar 7, 2011

In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-type header is automatically set to multipart/form-data.

Also, you don't have to create extra functions to build the query for your arrays, you already have that:

$query = http_build_query($data, '', '&');