Reputation: 181
I am using rest api's in my website..for that i have to make curl requests in every controller many times like that....
$data = array('id' => '01','user_name' => 'abc');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://abc.xyz.com/1.0/index.php/abc_ctrl/function");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
$output = curl_exec($ch);
curl_close($ch);
$output3 = json_decode($output);
functionality of every curl is same, like it makes a post call by sending a post data to rest controller..... i am tired of using same lines every time everyware...I want to make a post request function in config file or i dont know in main file, which accept parameter as url and post data and returns output...
so everytime i have to call that function in config and i got results...
Upvotes: 2
Views: 1572
Reputation: 2741
You may do it like this:
public function FunctionName()
{
$data = array('id' => '01','user_name' => 'abc');
$url = "http://abc.xyz.com/1.0/index.php/abc_ctrl/function";
$result = $this->CurlAPI($data,$url);
}
public function CurlAPI($data,$url)
{
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
$output = curl_exec($ch);
curl_close($ch);
$output3 = json_decode($output);
return $output3;
}
UPDATE:
You may also write this function in helper file as:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
public function CurlAPI($data,$url)
{
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
$output = curl_exec($ch);
curl_close($ch);
$output3 = json_decode($output);
return $output3;
}
Save this to application/helpers/ . We shall call it "new_helper.php"
This can be in your controller, model or view (not preferable)
$this->load->helper('new_helper');
echo CurlAPI($data,$url);
Upvotes: 1