Passing $_POST values with cURL
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 anarray()
: The data will be sent asmultipart/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 asapplication/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:
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
.
Another simple PHP example of using cURL:
<?php $ch = curl_init(); // Initiate cURL $url = "http://www.somesite.com/curl_example.php"; // Where you want to post data curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format $output = curl_exec ($ch); // Execute curl_close ($ch); // Close cURL handle var_dump($output); // Show output?>
Example found here: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/
Instead of using curl_setopt
you can use curl_setopt_array
.