How to make cUrl HTTP request in laravel 6

  1 year ago     Views:  2939  
Site Admin
4 Follows


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. if you like this article then please comment below. Thanks..


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments