In this guide, we will go through the different PHP clients you can use to connect to the Geekflare API.

Specifically, we will be covering using the Geekflare API with the file_get_contents function, Guzzle, HTTPful, and Symfony’s HTTPS client.

What is the Geekflare API?

Geekflare provides a set of free tools that you can use to monitor the performance of your website. These tools include a broken link analyzer, time to load, and a DNS checker. These tools can be accessed online via the web interface or the API.

The API is based on HTTP and can be accessed from any programming language with an HTTP client library. The API has a generous free tier that you can start using without needing to provide payment information.

What we are going to be building

We will write a script, executable from the command line, which will compute how long it takes to load the Google website and print them to the terminal. We will implement this simple program using different PHP HTTP clients to demonstrate what using the API looks like.

Specifically, we are going to use the built-in functions – file_get_contents() and php_curl, and the extension Guzzle PHP. However simple these examples may appear, they demonstrate the core concepts of using the Geekflare API.

Prerequisites

To follow along, you will need to know PHP beforehand and have it installed on your computer. Additionally, you will need Composer to manage extensions.

Lastly, you will also need a text editor to write code in. In my case, I am going to be using Visual Studio Code, a popular open-source text editor from Microsoft. You can download it from the Visual Studio Code website.

Geekflare API overview

The Geekflare API has different endpoints depending on what you want to do. The complete list of endpoints and their associated documentation can be found on the documentation page.

Creating a Geekflare account

To get started using the API, you will need to create an account by going to the API landing page and clicking the sign-up button. After sign-up is complete, you will be taken to the dashboard, where you will see your API key. The dashboard should be like the picture below. I have blacked out my API key for security reasons.

<img alt="Geekflare-Dashboard-1" data- data-src="https://kirelos.com/wp-content/uploads/2022/10/echo/Geekflare-Dashboard-1.jpg" data- height="743" src="data:image/svg xml,” width=”1368″>

In every API request you make, you will need to provide this key as a request header. Shortly, you will see how this can be done.

With a Geekflare account created and PHP installed, we can start creating the project.

Creating the project folder

First, create a folder where we will store the project files. After that, create the following files

  • .env
  • with_curl.php
  • with_file_get_contents.php
  • with_guzzle.php

After, run the following command to install the vlucas/phpdotenv and guzzlehttp/guzzle extension

composer require vlucas/phpdotenv guzzlehttp/guzzle

At this point, your project folder should look like this:

<img alt="Screenshot-from-2022-10-17-10-55-35" data- data-src="https://kirelos.com/wp-content/uploads/2022/10/echo/Screenshot-from-2022-10-17-10-55-35.png" data- height="207" src="data:image/svg xml,” width=”256″>

Now open the .env file and add the following line of code, replacing with your actual API key from the Geekflare dashboard:

API_KEY=

Using file_get_contents()

The first method we could use to make HTTP requests is to call the file_get_contents() function which is built into PHP. The function signature of the file_get_contents() function is as follows:

file_get_contents(path, include_path, context)

While the method is often used to read the contents of a file in local storage, we can use it to read a web resource, such as data returned by an API endpoint.

Now to get started, open the with_file_get_contents.php and add the boilerplate PHP code.

Next, we can get started with loading extensions. Add the following line of code to your file

require_once('vendor/autoload.php');

Next, we can load our environmental variables, which include the API key

$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();

Then, we can define the payload. This will be data we will send as part of the request body

$payload = json_encode([
    "url" => "https://www.google.com", 
    "proxyCountry" => "us",
    "followRedirect" => true
]);

We have created a payload variable and assigned it to a JSON string that contains the url, proxyCountry and followRedirect as properties.

The url property specifies the webpage whose load time we want to check.

The proxyCountry is the location of the server we want to use to make the request. In this case, we are using the USA server, but you can choose from India, China, the UK, and France. You can read the documentation for more details.

Then followRedirect specifies whether the proxy server should follow any redirections and measure the response time of the final response or the first redirect.

Afterward, we can create options that will configure our request by adding this code:

$options = [
    "http" => [
        "method" => "POST",
        "header" => array("Content-Type: application/json", "x-api-key : " . $_ENV['API_KEY']),
        "content" => $payload
    ] 
];

By doing this, we have created an options object that specifies that our HTTP method is POST, and we have a header that specifies two properties, the content type as JSON and the x-api-key as the API key that you specified in the .env file and has been loaded as an environmental variable.

Next, we can make the request by creating a stream where our options will be written to:

$context = stream_context_create($options);

Next, we call the file_get_contents() method to make the request and store the response as a variable.

$response = file_get_contents("https://api.geekflare.com/loadtime", false, $context);

We made the request to https://api.geekflare.com/loadtime. The false tells PHP not to use the path. And we pass the context we created to the method.

To display the response, we will use the output as follows.

echo "Loadtime: " . json_decode($response)->data->total . "n";

At the end of this, your file should look like this:

load();

    $payload = json_encode([
        "url" => "https://www.google.com", 
        "proxyCountry" => "us",
        "followRedirect" => true
    ]);

    $options = [
        "http" => [
            "method" => "POST",
            "header" => array("Content-Type: application/json", "x-api-key : " . $_ENV['API_KEY']),
            "content" => $payload
        ] 
    ];

    $context = stream_context_create($options);

    $response = file_get_contents("https://api.geekflare.com/loadtime", false, $context);

    echo "Loadtime: " . json_decode($response)->data->total . "n";
?>

When you run the file using the following command:

php with_file_get_contents.php

You will get the following output

Loadtime: 81

Using cURL

cURL is a command line utility that is used to make client-side URL requests. In PHP, it can be used using the php-curl utility. To begin using it, open the with_curl.php file and write the boilerplate PHP

Then let us import extensions and load the API_KEY environmental variable defined in the .env file

require_once('vendor/autoload.php');

$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();

Next, we will create a variable to store the headers of our object as an array where each individual element in the array is a specific header.

$header = ["Content-type: application/json", "x-api-key: " . $_ENV['API_KEY']];

We defined two headers, one for the content type and one for the API key.

Then we can define the body of the request.

$body = json_encode([
    "url" => "google.com",
    "proxyCountry" => "us",
    "followRedirect" => true
]);

After this, we can create a curl session using the curl_init() function. We can pass in the URL we want to make the request to as an argument to the function call.

$ch = curl_init("https://api.geekflare.com/loadtime");

Now we can put everything together by defining the header and body as options for the session. For this, we will use the curl_setopt_array() function

curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_POSTFIELDS => $body
]);

To make the request, we will call curl_exec() function

$response = curl_exec($ch);

We have stored the response in the $response variable, so we can close the session to free up system resources being used by the session.

curl_close($ch);

Lastly, we can print the response to the screen using var_dump.

var_dump($response);

In the end, your script file should look like this

load();

    $header = ["Content-type: application/json", "x-api-key: " . $_ENV['API_KEY']];

    $body = json_encode([
        "url" => "google.com",
        "proxyCountry" => "us",
        "followRedirect" => true
    ]);

    $ch = curl_init("https://api.geekflare.com/loadtime");

    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_POSTFIELDS => $body
    ]);

    $response = curl_exec($ch);

    curl_close($ch);

    var_dump($response);
?>

When we run the script using php with_curl.php, you should get the following output:

{"timestamp":1666083632547,"apiStatus":"success","apiCode":200,"meta":{"url":"google.com","followRedirect":true,"redirectedURL":"https://www.google.com/?gws_rd=ssl","test":{"id":"d20h1hb409qbfwm0g534l51asugpi5hl"}},"data":{"dns":12,"connect":17,"tls":6,"send":21,"wait":110,"total":114}}bool(true)

The request was completed successfully, and the API responded with JSON0 data. You can use this data as you please.

With Guzzle

In the last part of this tutorial, we will use Guzzle to write the script. As always, we start by inserting the PHP boilerplate inside of the with_guzzle.php

Then, we can import extensions and the Guzzle Client and Request Objects and load environmental variables.

require_once('vendor/autoload.php');

use GuzzleHttpClient;
use GuzzleHttpPsr7Request;

Next, we can load environmental variables.

$dotenv = DotenvDotenv::createImmutable(__DIR__);
$dotenv->load();

Afterward, we can instantiate a Guzzle HTTP client

$client = new GuzzleHttpClient();

Then we can proceed to create headers for our request

$headers = [
    'x-api-key' => $_ENV['API_KEY'],
    'Content-Type' => 'application/json'
];

Next, we can define the body of the request

$body = json_encode([
    "url" => "google.com",
    "proxyCountry" => "us",
    "followRedirect" => true
]);

We can then make the request by instantiating the Request class and passing in the API endpoint URL, header, and body.

$request = new Request('POST', 'https://api.geekflare.com/loadtime', $headers, $body);

Then we can send the request by adding this line of code:

$response = $client->sendAsync($request)->wait();

Once the request has been sent, we can receive the body of the request as follows

$response_body = $response->getBody();

In the end, we can decode the JSON response and print out the load time

echo "Loadtime: " . json_decode($response_body)->data->total . "n";

So, in the end, the file should look like this:

load();
    

    $client = new GuzzleHttpClient();

    $headers = [
        'x-api-key' => $_ENV['API_KEY'],
        'Content-Type' => 'application/json'
    ];

    $body = json_encode([
        "url" => "google.com",
        "proxyCountry" => "us",
        "followRedirect" => true
    ]);

    $request = new Request('POST', 'https://api.geekflare.com/loadtime', $headers, $body);

    $response = $client->sendAsync($request)->wait();

    $response_body = $response->getBody();

    echo "Loadtime: " . json_decode($response_body)->data->total . "n";
?>

And when you execute the script using the following command:

$php with_guzzle.php

And you will see the response:

Loadtime: 130

Conclusion

In this article, we went through the different clients you may want to use when creating a PHP project that will require the Geekflare API.

While the scripts in this project use the command line as the primary form of output, real-world projects could present the response on a web page or write it to a file. The example scripts in this article were simple, but they demonstrate the core concepts of using the Geekflare API. To use different APIs, you can change the endpoint and pass in different options in the request body.

You may also be interested in how to use Geekflare DNS Lookup API in Javascript.