PHP calling a POST request API using CURL

In this article we will see how can we call a post request using CURL. This curl request can send post data/json post data, disable SSL verification of host(when you call https), also you can send a Authorization Bearer token a secret shared by your API host.

Pre-Requisites: Install php-curl. Choose the below command according to your PHP Version.

sudo apt install php5-curl 
sudo apt install php7.0-curl

Now lets suppose we are having an API call that just does some function with the string you pass to it.

Now lets write the code.

<?php

#get the required variables
$slang = 'eng';
$tlang = 'hin';
$str = "Hello. How are you?";
#$token = 'LongsecretstringsharedbyyourAPIhost"

#parameters
$data = array("source_language"=>$slang, "target_language"=>$tlang, "text"=>$str);

#set the header type if you want to send json response
header('content-type: application/json');

#calling api here, replace with your URL
$ch = curl_init("http://getAPI/request/");
curl_setopt($ch, CURLOPT_POST, true);

#comment below line if you are not sending data as JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_PROXY, '');

#set  headers, remove authorization if you are not using one
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

#comment below line if you don't want to SSL Verification to false
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

#execute the curl request 
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
//echo 'Operation completed without any errors';
}
// Close handle
curl_close($ch);

#send response
echo $response;

With the above code you can call any API you want to and configure the CURL request as per your requirements.