How to send data between two server using curl in codeigniter?

by dalton_moen , in category: PHP Frameworks , 3 months ago

How to send data between two server using curl in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 3 months ago

@dalton_moen 

To send data between two servers using cURL in CodeIgniter, you can follow these steps:


Step 1: Install and Load cURL Library First, you need to install the cURL library in CodeIgniter. You can download the library from Github (https://github.com/philsturgeon/codeigniter-curl). After downloading, extract the files and place the 'curl.php' file in the following directory: 'application/libraries/'.


Next, open the 'application/config/autoload.php' file and add 'curl' in the 'libraries' section. This will load the cURL library automatically.


Step 2: Create a function in the Controller Open the controller where you want to send the data from and create a function that will handle the cURL request. For example, let's assume you want to send data from 'Server A' to 'Server B'.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public function send_data() {
   $url = 'http://serverB.com/receive_data'; // URL of the receiving server

   $data = array(
      'key1' => 'value1',
      'key2' => 'value2'
   ); // Data to send

   $ch = curl_init();

   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

   $response = curl_exec($ch);

   curl_close($ch);

   // Process the response from the receiving server if needed
   // ...

   echo $response;
}


In the above code, replace the 'http://serverB.com/receive_data' with the URL of the receiving server.


Step 3: Create a function in the Receiving Server On the receiving server, create a function that will handle the data received from 'Server A'. For example, let's assume you want to receive data in the 'receive_data' function of 'Server B' controller.

1
2
3
4
5
6
7
8
public function receive_data() {
   $received_data = $this->input->post();

   // Process the received data if needed
   // ...

   echo 'Data received successfully';
}


In the above code, the received data is stored in the '$received_data' variable.


That's it! You have now successfully sent data between two servers using cURL in CodeIgniter.