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


Then, we can use these functions in this way

$data =array(
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.

 $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?


  1. Bavotasan blog
  2. Davidwals Blog
  3. Stack overflow