03-Apr-2023
.
Admin
Hi Guys
Today, I will learn you how to send php cURL post request in codeigniter 4. we will show example of codeigniter 4 send php curl post request.than this tutorial will end your learning quest about PHP Curl POST in Codeigniter. When it comes to fetching data from the third-party endpoint in Codeigniter, then you can’t rely upon more than a CURL request on any other method.
You can go for php curl functions to deal with GET, POST, PUT, DELTE requests in Codeigniter with PHP CURL functions. It’s not just comfortable but also sole satisfying for web developers
We will show you a PHP cURL request example, along with that also help you deal with headers with authentication. We can take help of the following PHP curl functions to get the JSON response through API.
->curl_setopt():
->curl_init(): Initialize a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.
->curl_exec():It is recommended to call this method after evoking a cURL session along with every set session.
Example
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CurlController extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function curPostRequest()
{
/* Endpoint */
$url = 'http://www.localhost.com/endpoint';
/* eCurl */
$curl = curl_init($url);
/* Data */
$data = [
'name'=>'John Doe',
'email'=>'johndoe@yahoo.com'
];
/* Set JSON data to POST */
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
/* Define content type */
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
/* Return json */
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
/* make request */
$result = curl_exec($curl);
/* close curl */
curl_close($curl);
}
}
Let us check out the header authentication cURL example:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CurlController extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function curPostRequest()
{
/* Endpoint */
$url = 'http://www.localhost.com/endpoint';
/* eCurl */
$curl = curl_init($url);
/* Data */
$data = [
'name'=>'John Doe',
'email'=>'johndoe@yahoo.com'
];
/* Set JSON data to POST */
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
/* Define content type */
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json',
'App-Key: JJEK8L4',
'App-Secret: 2zqAzq6'
));
/* Return json */
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
/* make request */
$result = curl_exec($curl);
/* close curl */
curl_close($curl);
}
}
It will help you...
#Codeigniter