How do you pass $_POST
values to a page using cURL
?
To post data in the body of a request message using Curl, you need to pass the data to Curl using the -d or --data command line switch. The Content-Type header indicates the data type in the body of the request message.
To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.
Should work fine.
$data = array('name' => 'Ross', 'php_master' => true); // You can POST a file by prefixing with an @ (for <input type="file"> fields) $data['file'] = '@/home/user/world.jpg'; $handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); curl_exec($handle); curl_close($handle)
We have two options here, CURLOPT_POST
which turns HTTP POST on, and CURLOPT_POSTFIELDS
which contains an array of our post data to submit. This can be used to submit data to POST
<form>
s.
It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
takes the $data in two formats, and that this determines how the post data will be encoded.
$data
as an array()
: The data will be sent as multipart/form-data
which is not always accepted by the server.
$data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$data
as url encoded string: The data will be sent as application/x-www-form-urlencoded
, which is the default encoding for submitted html form data.
$data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
I hope this will help others save their time.
See:
curl_init
curl_setopt
Ross has the right idea for POSTing the usual parameter/value format to a url.
I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that:
$xml = '<?xml version="1.0"?><stuff><child>foo</child><child>bar</child></stuff>'; $httpRequest = curl_init(); curl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1); curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml")); curl_setopt($httpRequest, CURLOPT_POST, 1); curl_setopt($httpRequest, CURLOPT_HEADER, 1); curl_setopt($httpRequest, CURLOPT_URL, $url); curl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml); $returnHeader = curl_exec($httpRequest); curl_close($httpRequest);
In my case, I needed to parse some values out of the HTTP response header so you may not necessarily need to set CURLOPT_RETURNTRANSFER
or CURLOPT_HEADER
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With