How do you pass $_POST values to a page using cURL?
+19
A:
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);
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.
See:
@pix0r
Heh, need more coffee I think :) Thanks.
Ross
2008-08-26 15:38:34
A:
@Ross: typo, should be curl_exec($handle)
.
Perfectly simple example, thanks.
pix0r
2008-08-26 15:41:28
+9
A:
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 RETURNTRANSFER or HEADER.
Mark Biek
2008-08-26 15:44:43
This is not what the poster is asking, but it just happens to be exactly what I was looking for, thanks!
davr
2008-09-25 21:42:47
I'm glad someone else found it helpful.
Mark Biek
2008-09-26 12:31:17
your "curl_setopt($httpRequest, CURLOPT_HTTPHEADER, array("Content-Type: text/xml"));" solved something that took me couple of hours already! thanks a lot :)
alexeit
2009-09-01 11:06:28