PHP curl get request with parameters

Summary:

In this post, you will learn how to use a tool called PHP cURL get request to retrieve and send information from other websites, images, and files.

How to use authentication in the PHP cURL. This will help you to easily get data from different places over the internet.

Introduction:

In the world of building websites, it is important to be able to talk to other websites and URLs to get information. In PHP we can do this using the cURL tool that can help to send and receive information from different websites and URLs.

Prerequisites:

Before we begin, make sure the following prerequisites apply: 

Basic understanding of PHP programming. 

PHP is installed on your local machine or web server. 

Familiarity with the concepts of APIs and HTTP.

Getting Started with cURL:

Curl is like a special tool that helps a computer talk to other computers over the Internet.

It can send and receive information using web addresses.

In PHP, it can be used to automatically task the computer with web addresses and protocols.

But first, you need to make sure you have the curl turned on in your PHP.

1 – You can check if cURL is enabled by creating a PHP file and adding the following code:

<?php

if (function_exists('curl_version')) {

    echo "cURL is enabled or not in the server.";

} else {

    echo "cURL is not enabled on this server.";

}

?>

2. Another way to check whether cURL is enabled or not in PHP using the phpinfo() function. Create a file index.php and paste below code there and check.

<?php

phpinfo();

?>

Making a GET Request with Parameters:

Basics of PHP curl get Request

GET request is the default method in cURL if you are not defining any method then it will take as a GET request by default.

To make a GET request with parameters using PHP cURL, follow these steps:

Step 1: Initialize cURL Session

First, you need to initialize a cURL session using the curl_init() function:

$ch = curl_init();

Step 2: Set the URL with Parameters

Specify the URL you want to send the GET request to, along with any parameters. You can append parameters to the URL using the query string format:

$url = ‘https://api.example.com/data?param1=value1&param2=value2’;

curl_setopt($ch, CURLOPT_URL, $url);

Step 3: Configure cURL Options

Set additional cURL options to customize the request. For instance, you can set the option true or false to return the response data which is retrieved from the URLs instead of immediately displaying it in the browser:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Step4: Authentication

We can use two types of authentications in the curl header one is bearer authentication other one is basic authentication header format is different in both authentications.

Step 4a: Set Bearer Authentication in Header

For Bearer Token authentication we can pass the token directly in the authorization header with the keyword “Bearer” and space


//Authorization: Bearer your_token

// Set Authorization Header

$authorizationToken = 'Bearer your_token; // Replace with your actual token

$headers = array(

    'Authorization: '. $authorizationToken

);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

this is an example only to show how to use authentication in cURL if your API is open then no need to set this option. 

Step 4b: Set Basic Authentication in Header

In basic authentication, header authorization is constructed by base64 encoding of username and password in the format username: password

Authorization: Basic base64(username:password);

how to use HTTP Basic Authentication In basic authentication there will be a username and password or username and key  

Step 4: Execute the Request

Execute the cURL request using the curl_exec() function:

$response = curl_exec($ch);

Step 5: Close the cURL Session

Finally, close the cURL session using curl_close():

curl_close($ch);

Handling the Response:

The $response variable will now contain the data returned by the API. You can process, manipulate, and display this data as needed.

 Final example

// Initialize cURL

$ch = curl_init();

// Set the URL with Parameters

$url = 'https://jsonplaceholder.typicode.com/users/1';

curl_setopt($ch, CURLOPT_URL, $url);

// Configure cURL options

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the Request

$response = curl_exec($ch);

// Check for cURL errors

if(curl_errno($ch)) {

  echo 'cURL Error:'.curl_error($ch);

}

// Close the cURL session

curl_close($ch);

// Handling the Response

if ($response) {

 $result = json_decode($response, true);

 echo '<pre>';

 print_r($result);

} else {

  echo "No response received.";

}

Result

Array

(

    [id] => 1

    [name] => Leanne Graham

    [username] => Bret

    [email] => Sincere@april.biz

    [address] => Array

        (

            [street] => Kulas Light

            [suite] => Apt. 556

            [city] => Gwenborough

            [zipcode] => 92998-3874

            [geo] => Array

                (

                    [lat] => -37.3159

                    [lng] => 81.1496

                )

        )

    [phone] => 1-770-736-8031 x56442

    [website] => hildegard.org

    [company] => Array

        (

            [name] => Romaguera-Crona

            [catchPhrase] => Multi-layered client-server neural-net

            [bs] => Harness real-time e-markets

        )

)

Conclusion:

In this tutorial, we explored how to make GET requests with parameters using PHP cURL as well as how to use authentication in curl. you can seamlessly interact with APIs and web services, fetching and sending data over the internet efficiently for your web applications and rest APIs

%d bloggers like this: