Reputation: 17109
I'm setting up a custom e-commerce solution, and the payment system I'm using requires me to send HTTPS POSTS.
How can I do this using php (and CURL?), is it any different from sending http posts?
UPDATE:
Thanks for your replies, they've been very useful. I assume I will need to purchase an SSL certificate for this to work, and I will obviously do this for the final site, but is there any way for me to test this without buying one?
Thanks, Nico
Upvotes: 19
Views: 98798
Reputation:
PHP/Curl will handle the https request just fine. What you may need to do, especially when going against a dev server, is turn CURLOPT_SSL_VERIFYPEER off. This is because a dev server may be self signed and fail the verify test.
$postfields = array('field1'=>'value1', 'field2'=>'value2');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://foo.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
// Edit: prior variable $postFields should be $postfields;
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
$result = curl_exec($ch);
Upvotes: 44
Reputation: 96189
You can also use the stream api and http/https context options
$postdata = http_build_query(
array(
'FieldX' => '1234',
'FieldY' => 'yaddayadda'
)
);
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://example.com', false, $context);
You still need an extension that provides the SSL encryption. That can either be php_openssl or (if compiled that way) php_curl.
Upvotes: 12
Reputation: 268462
Similar question: POST to URL with PHP and Handle Response
Using the accepted solution (Snoopy PHP Class), you can do something like the following:
<?php
$vars = array("fname"=>"Jonathan","lname"=>"Sampson");
$snoopy = new Snoopy();
$snoopy->curl_path = "/usr/bin/curl"; # Or whatever your path to curl is - 'which curl' in terminal will give it to you. Needed because snoopy uses standalone curl to deal with https sites, not php_curl builtin.
$snoopy->httpmethod = "POST";
$snoopy->submit("https://www.somesite.com", $vars);
print $snoopy->results;
?>
Upvotes: 1
Reputation: 655735
No, there is no much difference. Curl does everything necessary itself.
See the examples in the user comments on the curl_setopt
reference page how it’s done.
Upvotes: 2
Reputation: 44992
If you are using curl, you can pass in the -d switch for your parameters. This results in using an HTTP post. Something like
curl http://foo.com -d bar=baz -d bat=boo
would result in an HTTP post to http://foo.com with the appropriate parameters
Upvotes: 1