How to Send GET and POST cURL request in CodeIgniter 4

The CURLRequest class that comes pre-installed in Codeigniter 4 makes it easy to send cURL request from the application.

It allows you to make requests via GET, POST, PUT, and other methods on various endpoints.

With this blog post, you will be able to understand about sending cURL GET and POST request using CURLRequest Class in CodeIgniter 4 and implement it in your project.

How to Send GET and POST cURL request in CodeIgniter 4


Contents

  1. Create API
  2. Send GET request
  3. Send POST request
  4. Add Header with request
  5. Conclusion

1. Create API

Create api.php file to handle cURL GET and POST requests and return response.

If $request == 1 means it is GET request then assign first_name, last_name, and email in $response Array and return it in JSON format.

If $request == 2 means it is POST request then read POST data and assign to the $response Array and return it in JSON format.

Completed Code

<?php

$request = 0;
if(isset($_GET['request'])){
   $request = $_GET['request'];
}

// GET request
if($request == 1){
   $response = array();

   $response['first_name'] = 'Arjun';
   $response['last_name'] = 'singh';
   $response['email'] = 'arjun@makitweb.com';

   echo json_encode($response);
   die;
}

// POST request
if($request == 2){
   // Read POST data
   $data = json_decode(file_get_contents("php://input"));

   $first_name = $data->first_name;
   $last_name = $data->last_name;
   $email = $data->email;

   $response['first_name'] = $first_name;
   $response['last_name'] = $last_name;
   $response['email'] = $email;

   echo json_encode($response);
   die;
}

2. Send GET request

Open your controller where you want to write a cURL request.

Assign API request URL to $apiURL and create an instance of Service class – \Config\Services::curlrequest() and assign to $client.

Send Request –

To send a GET request call get() method and pass 2 parameters –

  • $apiURL
  • An Array that contains 'debug' => true. This will write an error in the server error log.

Read Response –

The cURL request will return Response object using this read response data –

  • statuscode – $response->getStatusCode()
  • reason – $response->getReason()
  • body – $response->getBody()

If statuscode is 200 then read the body data. I am using json_decode() because from api.php returning JSON response. If you are not returning a JSON response then remove it.

After decoding read values and assign them to the variable. Print the variable values.

Completed Code

<?php 
namespace App\Controllers;

class PageController extends BaseController{
    
   // cURL GET request
   public function getrequest(){

       $apiURL = 'http://localhost/apis/api.php?request=1';

       // Instance
       $client = \Config\Services::curlrequest();
       
       // Send request
       $response = $client->get($apiURL,['debug' => true]);

       // Read response
       $code = $response->getStatusCode();
       $reason = $response->getReason(); // OK

       if($code == 200){ // Success

          // Read data 
          $body = json_decode($response->getBody());

          $first_name = $body->first_name;
          $last_name = $body->last_name;
          $email = $body->email;

          echo "first_name : ".$first_name."<br>";
          echo "last_name : ".$last_name."<br>";
          echo "email : ".$email."<br>";
       }else{
          echo "failed";
          die;
       }

   }

}

3. Send POST request

Assign the request URL to $apiURL and create an instance of the Service class.

Send Request –

In postData Array specify data that need to send from the cURL request.

To send POST request call post() method where pass 2 parameters –

  • $apiURL, and
  • An Array that contains ['debug' => true,'json' => $postData] –  Pass $postData in’json' key.

Read response –

Reading response step is the same as GET request.

Completed Code

<?php 
namespace App\Controllers;

class PageController extends BaseController{
     
    // cURL POST request
    public function postrequest(){
        $apiURL = 'http://localhost/apis/api.php?request=2';
        $client = \Config\Services::curlrequest();

        $postData = array(
           'first_name' => "Yogesh",
           'last_name' => "singh",
           'email' => "yogesh@makitweb.com",
        );

        // Send request
        $response = $client->post($apiURL,['debug' => true,'json' => $postData]);

        // Read response
        $code = $response->getStatusCode();
        $reason = $response->getReason();

        if($code == 200){ // Success

           // Read data 
           $body = json_decode($response->getBody());

           $first_name = $body->first_name;
           $last_name = $body->last_name;
           $email = $body->email;

           echo "first_name : ".$first_name."<br>";
           echo "last_name : ".$last_name."<br>";
           echo "email : ".$email."<br>";

        }else{
           echo "failed";
           die;
        }

    }

}

4. Add header with Request

I am sending the Header with a POST request.

Specified 2 headers in $headerData Array. While sending POST request specified headers in the 2 parameters –

'headers'=>$headerData,

Completed Code

public function postrequest(){
    $apiURL = 'http://localhost/codeigniter4/api.php?request=2';
    
    $client = \Config\Services::curlrequest();

    $postData = array(
       'first_name' => "Anil",
       'last_name' => "sharma",
       'email' => "anil@makitweb.com",
    );

    // Header data
    $headerData = array(
       'Content-Type' => 'application/json',
       'Accept' => 'application/json',
    );

    // Send request
    $response = $client->post($apiURL,[
       'debug' => true,
       'headers'=>$headerData,
       'json' => $postData
    ]);

    // Read response
    $code = $response->getStatusCode();
    $reason = $response->getReason();

    if($code == 200){ // Success

       // Read data 
       $body = json_decode($response->getBody());

       $first_name = $body->first_name;
       $last_name = $body->last_name;
       $email = $body->email;

       echo "first_name : ".$first_name."<br>";
       echo "last_name : ".$last_name."<br>";
       echo "email : ".$email."<br>";

    }else{
       echo "failed";
       die;
    }

}

5. Conclusion

Using the examples, you can easily implement cURL request in your project. If cURL not sending then check if the cURL library is enabled or not in the server. If not then enable it otherwise use the error log to debug it.

You can learn more about this class from here.

If you found this tutorial helpful then don't forget to share.

Leave a Comment