Laravel Http Curl Request Example

1320 views 9 months ago Laravel

cURL is a solid and simple tool that allows transferring data from and to any server with command line using various protocols including HTTP. Curl is a command-line tool that allows us to do HTTP requests from shell. It also covers many other protocols, like FTP, though they go beyond the scope of this tutorial.

In this tutorials we will share with you how to make cUrl request in laravel, this is most common topic and functionality. help of cUrl you can make any type request like GET, POST, OPTION etc... but basically in this tutorials we show you 2 most common HTTP request with cUrl.

cUrl is mostly use in laravel when you work with any third party API. in laravel application cUrl is provide very easy way to functionality for call any API with any HTTP method. most off developer choose cUrl for call API as well as make any API.

Make GET Request

<?php
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://example.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_TIMEOUT => 30000,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
    	// Set Here Your Requesred Headers
        'Content-Type: application/json',
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    print_r(json_decode($response));
}

Make POST Request

<?php
// Make Post Fields Array
$data1 = [
    'data1' => 'value_1',
    'data2' => 'value_2',
];
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://example.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30000,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode($data2),
    CURLOPT_HTTPHEADER => array(
        // Set here requred headers
        "accept: */*",
        "accept-language: en-US,en;q=0.8",
        "content-type: application/json",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    print_r(json_decode($response));
}

We hope these small tutorials help everyone.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]