use-curl-to-send-data

[Practice] How to Send Data Between 2 Server with Curl

I have two pieces of different servers IP and I want the server A can store data in MySQL database server B. step I take is give grant to server A (server address A) by registering the IP address in a remote MySQL server B , so that the server B is recognized and granted.

The measures mentioned above it seems easy, but when all is in perfect settings, they do not work and the exchange of data could not be done. Failed.

Is there another way to send data between the server?

Then, I tried using CURL. PHP This feature allows us to send data with POST method with a simple interface. CURL could be assumed as a full browser, you can provide the name of the browser, for example the name of the engine  firefox (agent) or google chrome. Curl can send the POST or GET method. More information about the curl can be read here. Generally, each server has a feature curl.
Ok, back to coding. We will create a function to make it easier.

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);
   
}

Then, we can use these functions in this way

<?php
$data =array(
 'foo'=>'bar',
 'fruit'=>'apple'
);
post_to_url("http://serverB.com/getdata.php", $data);
?>

Then, we will create a file with the name getdata.php placed in the server B.

<?php
 $foo=$_POST['foo'];
 $fruit = $_POST['fruit'];

///-- save to your database

?>

You can capture data that has been sent from the server A and then put it into a database. Simple right?

Resource

  1. Bavotasan blog
  2. Davidwals Blog
  3. Stack overflow
Web developer, big fan of CakePHP, loving wordpress soo much. You can found him on Google+ and Facebook. Dont forget to follow him on Twitter.
Posts created 562

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top