Post to a URL Using cURL and PHP

A client needed me to write a script that would collect information from their database and post it to a specific URL, just like it was being submitted by a form. I tried messing around with the idea and the solution I came up with required the cURL library for PHP.
The script is pretty simple. First, let’s collect some data into an array:

$data = array(
   "name" => "c.bavota",
   "website" => "http://bavotasan.com",
   "twitterID" => "bavotasan"
);

Now comes the function to post the data to an URL using cURL:

function post_to_url($url, $data) {
   $fields = '';
   foreach($data as $key => $value) {
      $fields .= $key . '=' . $value . '&';
   }
   rtrim($fields, '&');
   $post = curl_init();
   curl_setopt($post, CURLOPT_URL, $url);
   curl_setopt($post, CURLOPT_POST, count($data));
   curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
   $result = curl_exec($post);
   curl_close($post);
}

The function takes two parameters: the URL and the data array. If you need the returning results from the URL you’re posting to, you can remove that last curl_setopt line.

   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);

With all that in place, now you can easily call the function, passing the two required parameters.

function post_to_url($url, $data) {
   $fields = '';
   foreach($data as $key => $value) {
      $fields .= $key . '=' . $value . '&';
   }
   rtrim($fields, '&');
   $post = curl_init();
   curl_setopt($post, CURLOPT_URL, $url);
   curl_setopt($post, CURLOPT_POST, count($data));
   curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
   $result = curl_exec($post);
   curl_close($post);
}
$data = array(
   "name" => "c.bavota",
   "website" => "http://bavotasan.com",
   "twitterID" => "bavotasan"
);
post_to_url("http://yoursite.com/post-to-page.php", $data);

On the receiving end, you can treat it just like you would if you were using a form to post the information to that specific URL.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie