HomeTutorialCodeigniterHow to implement Curl in Codeigniter 4 Get & POST Request Tutorial

How to implement Curl in Codeigniter 4 Get & POST Request Tutorial

In this tutorial, we will explain how to send or make a CURL POST request in Codeigniter 4, as well as a CURL GET request. A client URL is known as a cURL. PHP’s cURL library lets you make HTTP requests. In PHP, libcurl is supported, which allows connection and communication with different types of servers.

If you want to fetch data from the third-party endpoint in Codeigniter 4, then you can only use CURL requests.

Are you dealing with REST APIs or third-party web services? You can use PHP curl functions in Codeigniter to handle GET, POST, PUT, and DELETE requests. For web developers, it is not only comfortable, but also very satisfying.

Method 1 : PHP cURL request

This tutorial will show you how to make a PHP cURL request, along with dealing with headers. To get a JSON response through API, we can use the following PHP curl functions:

  • curl_setopt(): Sets a cURL transfer option

  • curl_init(): Creates a new session and returns a cURL handle for use with curl_setopt(), curl_exec(), and curl_close().

  • curl_exec(): The method should be called after every cURL session is invoked.

For Curl Request we can use Codigniter4 Curl Request Class or Can be use any third party class. In this tutorial we will cover both way.

Php Curl Convert USD to Bitcoin Example

<?php

namespace App\Controllers;

class Test extends BaseController{

      public function get_btc_price(){
           $amount = '1000';  // USD Amount
           $url ="https://api.coingate.com/v2/rates/merchant/USD/BTC";
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
           curl_setopt($ch, CURLOPT_URL,$url);
           $result=curl_exec($ch);
           curl_close($ch);
           $data = json_decode($result, TRUE);
           $live_price= $data;
           $btc_price = round ( $amount / 100 * $live_price , 8 ) *100 ;
           echo $btc_price ;

      }


}

Method 2 : Codigniter 4 Curl Request Class

The Codigniter4 CURLRequest class is a lightweight HTTP client based on CURL that allows you to talk to other web sites and servers. It can be used to get the contents of a Google search, retrieve a web page or image, or communicate with an API, among many other things.

Loading the Library

The library can be loaded either manually or through the Services class.

To load with the Services class call the curlrequest() method:

<?php

$client = \Config\Services::curlrequest();

You can pass in an array of default options as the first parameter to modify how cURL will handle the request. The options are described later in this document:

<?php

$options = [
    'baseURI' => 'http://example.com/api/v1/',
    'timeout' => 3,
];
$client = \Config\Services::curlrequest($options);

Working with the Library

Working with CURL requests is simply a matter of creating the Request and getting a Response object back. It is meant to handle the communications. After that you have complete control over how the information is handled.

Making Requests

Most communication is done through the request() method, which fires off the request, and then returns a Response instance to you. This takes the HTTP method, the url and an array of options as the parameters.

<?php

$client = \Config\Services::curlrequest();

$response = $client->request('GET', 'https://api.github.com/user', 
[ 'auth' => ['user', 'pass'], ]);

echo $response->getStatusCode();

Since the response is an instance of CodeIgniter\HTTP\Response you have all of the normal information available to you.

Method 3 : Third Party Curl Request Class

This class is one of my favorite. Its  very easy to manage. PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs.

Requirements

Third Party PHP Curl Class works with PHP 7.4, 8.0, and 8.1.

Installation

To install PHP Curl Class, run the following command:

composer require php-curl-class/php-curl-class

To install the latest commit version:

How to use

CodeIgniter 4 Curl Get Request Example

<?php

namespace App\Controllers;
use Curl\Curl;

class Test extends BaseController{

    public function index(){

         $curl = new Curl(); 
         $curl->get('https://www.example.com/');

         if ($curl->error) {
            echo 'Error: ' . $curl->errorMessage . "\n";
         } else {
            echo 'Response:' . "\n";
            var_dump($curl->response);
         }
 
    }


}
CodeIgniter 4 Curl Post Request Example
<?php

namespace App\Controllers;
use Curl\Curl;

class Test extends BaseController{

    public function index(){

         $url = 'https://www.example.com/';
         $payload = ['auth_key' => 'anything']

         $curl = new Curl(); 
         $curl->setHeader('Content-Type', 'application/json');
         $payload = json_encode( $fields );
         $curl->post($url, $payload);
         $result = $curl->response;
         $curl->close();
         var_dump($result); 
 
    } 


}

If you have any questions, please leave them in the comments.

Donate

Ankit Bhandari
Ankit Bhandarihttps://www.bhandariankit.com
My mission is to empower people to take control of their health and fitness by following a healthy, enjoyable lifestyle that not only gives them the body they’ve always wanted, but enables them to live a long, vital, disease-free life.
RELATED ARTICLES

Leave a Reply

Most Popular

Recent Comments