Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curl POST format for CURLOPT_POSTFIELDS

Tags:

post

php

curl

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); 
like image 939
Ken Avatar asked Mar 07 '11 20:03

Ken


People also ask

What is Curlopt_postfields?

CURLOPT_POSTFIELDS. The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'.

What is Curlopt_returntransfer in cURL?

CURLOPT_RETURNTRANSFER: Converts output to a string rather than directly to the screen. CURLOPT_HTTPHEADER: Request header information with an array of parameters, as shown in the example of "Browser-based redirection"


1 Answers

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, '', '&'); 
like image 180
kodeart Avatar answered Oct 21 '22 07:10

kodeart