Curl GET using Codeigniter

Here’s a sample code on how do a curl GET using the Codeigniter v2 framework.

This is an MVC PHP framework. If you are reading this, i assume you know about Codeigniter and if you do not, you can read up on the documentation here

First, you create a controller to handle the process and then load the necessary libraries within the constructor of the controller.

class process extends CI_Controller {

// Code goes here within the controller.

}

Next we create an index method within the controller that gets called when you point your address

If you have a freshly installed CI project and you have not updated your .htaccess file to strip out index.php

http://yourhost/index.php/process

else

http://yourhost/process

Within this method i created a $request_headers array variable that would hold the header information the your api.


public function index()
{
$secretKey = "sk_test_1234567";

$url = "https://api.mywebsite.com/transaction/verify/" . $this->refcode;

// append the header putting the secret key and hash

$request_headers = array();
$request_headers[] = 'Authorization: Bearer ' . $secretKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);

if (curl_errno($ch))
{
print "Error: " . curl_error($ch);
}
else
{
// Show me the result

$transaction = json_decode($data, TRUE);

curl_close($ch);

var_dump($transaction['data']);

}

 

Here’s the complete code . Enjoy. 🙂


class process extends CI_Controller {

public function __construct()
{
// created the construct so that the helpers, libraries, models can be loaded all through this controller
parent::__construct();
$this->load->helper('url');
$this->load->library('xmlrpc');
$this->load->library('xmlrpcs');
$this->refcode = $this->session->userdata('refcode');
}

public function index()
{
$secretKey = "sk_test_1234567";

$url = "https://api.mywebsite.com/transaction/verify/" . $this->refcode;

// append the header putting the secret key and hash

$request_headers = array();
$request_headers[] = 'Authorization: Bearer ' . $secretKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);

if (curl_errno($ch))
{
print "Error: " . curl_error($ch);
}
else
{
// Show me the result

$transaction = json_decode($data, TRUE);

curl_close($ch);

var_dump($transaction['data']);

}
}
}`

 

CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.

This sample code is based on Codeingiter v2.14.

9 months ago

Leave a Reply