In this article i will show you to send curl post and get request with headers in laravel. As we know curl
basically a command line software which used for transferring data between servers and php provides its inbuilt library in php core.
In laravel or php to access the third party data we need to access the data using the APIs, we send a request to another server means outside our application and they respond with preformatted structure. Post request is used to send bulk data and upload the files from client to server and here we are going to send to post request from one server to another server.
In this article we will use a simple example to send post and get request in laravel curl. To accomplish this task we will create a project and route to send the request to third party application
So let’s start the tutorial of send curl post and get request in laravel
Method 1 : Send POST Request Using curl with headers
In this method we will send post request with Content-Type
header
<?php
use Illuminate\Support\Facades\Route;
Route::get("/send-request",function(){
$postdata = json_encode(
array(
"name"=> "morpheus",
"job"=>"leader"
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://reqres.in/api/users");
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
dump($httpcode);
dump(json_decode($output));
return $output;
});
here we used curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
to set the headers
Method 2 : Send GET Request Using curl with Headers
Second method is to use the Curl to send the GET request with headers
<?php
use Illuminate\Support\Facades\Route;
Route::get("/send-request",function(){
$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: Bearer $auth_token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sampleapis.com/cartoons/cartoons2D");
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
dump($httpcode);
dump(json_decode($output));
return $output;
});
Here we added Authorization header in request header
Output :