In this article i will show you to send file_get_contents post and get request with headers in laravel. As we know file_get_contents is php inbuilt core function used to access the local file and remote URLs. File_get_contents is used to read the file in different modes and to send the request on remote sites with header context.
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 file_get_contents. 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 file_get_contents Post and Get Request with Headers in laravel
Method 1 : Send POST Request Using file_get_contents 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(){
//if want to send request like form
$postdata = json_encode(array(
"name"=> "morpheus",
"job"=>"leader"
));
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
// 'header' => 'Content-Type: application/x-www-form-urlencoded', if want to send request like form
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://reqres.in/api/users', false, $context);
dump($http_response_header);
dump(json_decode($result));
return 1;
});
here we used 'header' => 'Content-Type: application/json',
to set the headers or set Bearer Authorization
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Authorization: Bearer $auth_token',
'content' => $postdata
)
);

Method 2 : Send GET Request Using file_get_contents 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(){
$response = file_get_contents("https://api.sampleapis.com/cartoons/cartoons2D");
dump($http_response_header);
dump(json_decode($response));
return $response;
});
Output :

Also Read : How to Send Curl Post and Get Request with Headers in Laravel ?