Run a cURL GET Request in PHP

cURL GET Request in PHP – Code Snippet

Here’s a featured snippet from the article. The example performs a basic cURL GET request in PHP.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

Don’t know what cURL is all about? Stick to this article and learn what is cURL in PHP?

Relevant Content: What is cURL in PHP?

cURL (Client URL) is a command-line tool that communicates with a server. It simplifies sending data to and from the server using short commands right from the shell. On top of that, it supports many different protocols, including HTTP/HTTPs, the most widely used protocol on the internet.

cURL GET Request in PHP

Learn more about HTTP at FuelingPHP.

So if you’re a developer trying to test a web server readily from your local machine, cURL could be your go-to tool.

How do I know if cURL is Installed?

cURL is available out of the box in most shells. Following are the commands to know if cURL is installed in your system. 

How do I know if cURL is Installed?

How to run a cURL Request through the terminal

cURL expects a URL parameter for reaching out to the right resource on the web. Running a cURL request is straightforward. Let’s look at a very basic cURL GET

cURL GET Request in PHP

So, the command sends an API request using cURL. You can also send a cURL request with parameters. Here is an overview of some parameters that cURL accepts.

cURL request with parameters

The above section is an overview of cURL and a basic example using shell commands. This preliminary section is in no way a complete guide on cURL commands. The idea was to set the context before we explored how to use cURL in PHP. 

Scenario: PHP cURL Get Posts from API

Develop a basic frontend that would list information about Posts (Thinks of a Facebook post, maybe).

The Posts data is available through an API. The application would have to communicate with the API and fetch the posts. Once it has the data, it needs to populate it in HTML. Here is a wireframe of the front end.

HTML wireframe

Thus the article explores how to get data from API using cURL in PHP. Before going about this problem, let’s learn all about cURL GET request using PHP. 

Using libcurl in PHP for CURL Requests

The fundamental idea of cURL is just the same. PHP supports libcurl, which is the underlying library for cURL.

PHP cURL comes with a bunch of functions – see the documentation. Some functions are fundamental for the lifecycle of a typical cURL request in PHP.

What is cURL in PHP?
curl_init(); //Initializes a cURL session and returns a cURL handler.
curl_setopt(); //Sets up the options for the cURL session.
curl_exec(); //Executes the cURL session.
curl_close(); //Closes the session and deletes the variable (recommended use)

Know more about the functions through the official documentation.

Send a cURL GET Request in PHP using curl_init() and curl_exec()

Sending a basic GET request with PHP cURL requires a few lines of code. The following example sends a cURL GET Request using PHP.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

We initialize a cURL handler with a URL in a few lines of code and execute the cURL session. Finally, the example prints the output to the console, which is as follows.

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Send a PHP cURL GET Request with Parameters using curl_setopt()

PHP curl_setopt() adds many options to modify the cURL request. Check out the full list of options here. The following example revisits the last one – with some options now

 
$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Converts output to a string.
curl_setopt($curl, CURLOPT_HEADER, false); //Excludes headers in the output.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 50); //50 seconds of timeout
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

The example adds several options before executing the cURL GET request in PHP. 

Send a PHP cURL GET Request with Parameters using curl_setopt_array()

An alternative way of binding options to the cURL handler is by passing in an array of options. This approach is suitable when you have to add many options and thus don’t want to call curl_setop() repeatedly.

Let’s refactor the last example using curl_setopt_array() this time.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init(); //Initializes a cURL session and returns a cURL handler.
 
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_CONNECTTIMEOUT => 50
]);
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

Looks clean! Also, observe that the example passes in the URL in the options array. So, it is not absolutely necessary to pass the URL at the time of curl_init().

How to get cURL Response Headers in PHP?

Using curl_getinfo() and headers offset, PHP gets the response header from the cURL transfer. The following example retrieves the header from the response.

$url = "https://jsonplaceholder.typicode.com/posts";
$curl = curl_init();
 
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
 
$response = curl_exec($curl);
 
$header_offset = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_offset);
 
echo json_encode($header);

Here’s the output.

HTTP/2 200 
date: Mon, 29 Aug 2022 18:30:54 GMT
content-type: application/json; charset=utf-8
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1660077104
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: max-age=43200
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"6b80-Ybsq/K6GwwqrYkAsFxqDXGC7DoM"
via: 1.1 vegur
cf-cache-status: HIT
age: 11827
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=Z35VpEP7RCT%2Bm3UfWagbrpUXu28I1qUuuW0NWrsA4bId4K4lkJY01s0YnIo%2F6H6DGTSg32ZryBFezI0EcNwy%2BcI61dz32P26u9LZLMS6XtRoLb1W8AeW093T3yAw2OVROsef8Z2yS1PCmqPNKWFa"}],"group":"cf-nel","max_age":604800}
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 74275c4d5bcaa083-SIN
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

[Solution]: How to call REST API using cURL in PHP?

It is time to put together all we have learned so far and use a cURL GET request in PHP to fetch Posts from the API. Once we have the results, we can populate the HTML template.

Here’s the solution.

$url = "https://jsonplaceholder.typicode.com/posts";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
$response = curl_exec($curl);
 
if (curl_errno($curl)) {
    $response = curl_error($curl);
}
 
curl_close($curl);
 
 
echo "<html>
    <head>
        <title>Posts</title>
        <style>
            div {
                max-width: 500px;
                height: 150px;
                border: 3px solid black;
                margin: 1px 1px;
            }
        </style>
    </head>
    <body>";
 
    if(isset($error)) {
        echo "<div>Error in loading posts</div>";
    }
    else{
        $posts = json_decode($response, true);
        foreach($posts as $post)
        {
            echo "<div><p>".$post["title"]."</p><p>".$post["body"]."</p>"."</div>";
        }
    }
echo "</body>
</html>";

Running this script on a server renders the resulting HTML as follows.

cURL GET Request in PHP

Phew! That was a lot of content to cover. Let’s jump to the conclusion now.

Getting CURL Get Requests in PHP Recap

This article explores how to run a cURL GET response in PHP. The article includes an introductory section on cURL and then features a problem scenario related to building a PHP application. This application uses cURL to fetch data from an API.

Then the article explores how to use cURL in PHP and build momentum by incrementally adding things to the examples. Finally, the article features a solution to the scenario problem after the demo examples. Hope you’ve enjoyed this article. Stay tuned to learn more at FuelingPHP.

Classes and Functions Mentioned

cURL – (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) cURL is a PHP library that uses liburl under the hood. The library comes with a bunch of functions. The functions that have been used in this article are the most commonly used functions of this library. The library as a whole is quite stable and performant. It has been available right from PHP 4.0.2 up to PHP 8.

json_decode: (PHP 5.2+, 7, 8) This function is quite handy in transforming JSON to PHP array or object. It is commonly used in various scenarios where transformation is necessary. Besides, it is a core function and based on its extensive use over time, it seems depreciation is unlikely in the near or distant future.


Article Categories

Article Tags

© 2022 Confident.Systems