GET And POST data using CURL

cURL is a command-line tool to transfer data between servers.

 It supports various protocols such as HTTP, HTTPS, FTP, FTPS, IMAP, etc. 

GET Method:

?php

// Initiate curl session in a variable (resource)

$curl_handle = curl_init();

$url = "";

// Set the curl URL option

curl_setopt($curl_handle, CURLOPT_URL, $url);

// This option will return data as a string instead of direct output

curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);

// Execute curl & store data in a variable

$curl_data = curl_exec($curl_handle);

curl_close($curl_handle);

$response_data = json_decode($curl_data);

// print_r($response_data);

$user_data = $response_data->data;

?>

PHP

First, we need to initiate a curl and pass your URL. 

Then execute CURL & store received data. 

As API URL returns JSON data, we need to decode it using json_decode. 


POST Method:

An HTTP POST is often used to create new content.

?php

// User data to send using HTTP POST method in curl

$data = array('name'=>'Rajamohan','mobile'=>'9999999999', 'age' => '25');

$data_json = json_encode($data);

// API URL to send data

$url = '';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

curl_setopt($ch, CURLOPT_POST, 1);

// Pass user data in POST command

curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute curl and assign returned data

$response = curl_exec($ch);

// Close curl

curl_close($ch);

print_r ($response);

?>

Sign In or Register to comment.