Execute HTTP POST Request Using PHP CURL

Recently I had a weird problem where I was setting up two sites to use Barclays ePDQ, however the post back URL for both sites were completely different so I could not simply format a PARAMVAR so ePDQ would post to the right place.

I finally concluded that I needed a central location for ALL post backs and then filter where the post back needed to go and forward the $_POST off to the correct location, to do this I concluded would require CURL as it is the most flexible HTTP request package for PHP.

The below script will take the $_POST variables from the page request and then POST them to another URL – this URL could be another file on the server, or even another server. The results of the POST are returned by CURL so you could even do much more than this example explains.

<?php
$url = "http://www.site.com/postfile.php";
//url-ify the data for the POST
foreach($_POST as $key => $value) {
 $fields_string .= $key . '=' . urlencode($value) . '&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
?>

This solution is working really well so it was impossible not to share it!

Facebooktwitterredditpinterestlinkedinmail
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
, , ,
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments