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.