in

How to Use the Geekflare API with PHP Clients

Geekflare provides a robust API that allows you to integrate their suite of website monitoring and optimization tools into your own applications. Their API supports a wide range of clients including PHP.

In this comprehensive guide, we will explore how to use the Geekflare API with PHP by covering the following topics:

  • Overview of the Geekflare API
  • Preparing your development environment
  • Authentication with API keys
  • Making requests with Guzzle
  • Handling responses
  • Building a load time checker app
  • Additional endpoints and use cases

By the end, you‘ll have a solid foundation for building PHP applications powered by the Geekflare API.

Overview of the Geekflare API

Geekflare offers a suite of performance and security tools for websites including:

  • Load time – Test website load speed from multiple geographic locations.

  • Uptime Monitoring – Get notified when your site goes down.

  • PageSpeed Insights – Find performance bottlenecks.

  • Broken Link Checker – Identify dead links on your site.

  • SSL Checker – Monitor SSL certificate expirations.

  • DNS Lookup – Lookup DNS records.

  • Ping Test – Check connectivity to your website.

  • And more…

Geekflare provides both a web interface and API access to these tools. The API allows you to integrate their services into your own PHP applications.

For example, you could build a custom dashboard that displays your website‘s load time and uptime status. Or create alerts when SSL certificates are about to expire.

The API uses predictable RESTful URLs and returns JSON-encoded responses. It uses standard HTTP response codes and includes CORS support so it can be called from client-side JavaScript code.

Authentication is handled via API keys. Let‘s look at how to get setup with an API key next.

Preparing Your Development Environment

To call the Geekflare API from PHP, you will need:

  • Access to a PHP 7.1+ development environment
  • Composer to install PHP dependencies
  • A Geekflare account and API key

Install PHP and Composer

Make sure you have PHP 7.1 or newer installed. You can verify this by running:

php -v

You‘ll also need Composer, which is the dependency manager for PHP. Install instructions can be found at getcomposer.org.

Verify Composer is installed properly:

composer --version

Sign Up for a Geekflare Account

First, you‘ll need to sign up for a free Geekflare account at https://mcngmarketing.com.

Once registered, you can grab your unique API key from the dashboard:

Geekflare Dashboard

Make sure to keep this key private as it provides full access to your Geekflare account.

With our environment setup, we can start making API requests!

Authenticating with the API Key

The Geekflare API uses API keys to authenticate requests.

You should pass your API key as a header in all requests:

# Replace with your actual key 
Authorization:Bearer 123456789

Here is an example using the PHP array syntax:

$headers = [
  ‘Authorization‘ => ‘Bearer ‘ . $_ENV[‘GEEKFLARE_API_KEY‘]  
];

Then pass the headers while making the request.

Never expose your API key directly in code! Instead, use an environment variable or credential storage to keep it separate.

For this guide, we‘ll use the .env file convention to store the key safely:

.env

GEEKFLARE_API_KEY=123456789

We can load it into our app with PHP‘s getenv():

$apiKey = getenv(‘GEEKFLARE_API_KEY‘);

Proper API key management is crucial for security.

Now let‘s look at making requests to the API.

Making API Requests with Guzzle

Guzzle is a popular HTTP client for PHP. It provides an intuitive interface for sending requests and handling responses.

First, install Guzzle using Composer:

composer require guzzlehttp/guzzle

Then here is an example request to the load time endpoint:

// Require the Guzzle autoloader
require ‘vendor/autoload.php‘; 

// Import Guzzle classes
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

// Create Guzzle client
$client = new Client();

// Prepare headers 
$headers = [
  ‘Authorization‘ => ‘Bearer ‘ . getenv(‘GEEKFLARE_API_KEY‘)    
];

// Prepare request data
$params = [
  ‘url‘ => ‘https://www.example.com‘,
  ‘location‘ => ‘London‘ 
];

try {

  // Send request
  $response = $client->request(‘POST‘, ‘https://api.mcngmarketing.com/loadtime‘, [
    ‘headers‘ => $headers,
    ‘json‘ => $params
  ]);

  // Handle response
  $body = $response->getBody();
  print_r(json_decode($body)); 

} catch (GuzzleException $e) {

  // Handle exceptions
  echo $e->getMessage();

}

Let‘s break down what‘s happening:

  • Import Guzzle classes with use statements
  • Create a Client instance
  • Prepare the headers with your API key
  • Define request params as a JSON array
  • Make a POST request to the loadtime endpoint
  • Pass headers and params
  • Handle response by decoding JSON body
  • Catch any Guzzle exceptions

The Geekflare API supports both GET and POST methods. Typically GET is used for retrieving data while POST allows sending data.

Guzzle also supports concurrent requests, middleware, events, and more. Refer to their excellent documentation for details.

Now let‘s look at handling API responses.

Processing API Responses

The Geekflare API returns JSON-encoded responses. Here is an example response from the load time endpoint:

{
    "timestamp": 1577322714552,
    "apiStatus": "success",
    "apiCode": 200,
    "meta": {
        "url": "https://www.example.com",
        "location": "London",
        "loadType": "desktop"
    },
    "data": {
        "dns": 162,
        "connect": 186, 
        "ttfb": 200,
        "download": 217,
        "total": 765
    }
}

The outer fields provide metadata like timestamps and status codes. The data field contains the load time metrics we want.

To access the data, decode the JSON using json_decode():

$body = $response->getBody(); 

// Decode JSON data
$data = json_decode($body, true);

// Access load time results 
$dns = $data[‘data‘][‘dns‘]; 
$total = $data[‘data‘][‘total‘];

echo "DNS lookup took {$dns}ms \n";
echo "Total load time was {$total}ms";

The 2nd parameter true returns an associative array instead of objects. This provides easier access to values by key.

You can loop through the data fields to output all results:

// Loop through metrics
foreach ($data[‘data‘] as $key=>$value) {
  echo "{$key}: {$value}\n"; 
}

This will print out each load time component.

Handling errors works similarly:

// Check for API error
if($data[‘apiStatus‘] === ‘error‘) {

  echo "API returned an error: " . $data[‘apiError‘];

}

The apiStatus will be error instead of success on failure.

Now let‘s put these concepts together to build an app!

Building a Load Time Checker App

To demonstrate using the Geekflare API in PHP, let‘s build a simple load time checker app.

It will:

  • Allow users to enter a URL
  • Fetch load time data from the API
  • Display results on a dashboard

We‘ll use basic PHP without any frameworks for simplicity.

index.php

<?php

// Load .env file
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Import Guzzle
require ‘vendor/autoload.php‘;
use GuzzleHttp\Client;

// Check for form submission
if ($_SERVER[‘REQUEST_METHOD‘] === ‘POST‘) {

  // Get URL
  $url = $_POST[‘url‘];

  // Call API  
  $loadTime = getLoadTime($url);

  // Display results
  displayResults($loadTime);

}

// Load time form
displayForm();


/**
 * Fetch load time data from API
 */
function getLoadTime($url) {

  // Geekflare API credentials 
  $apiKey = getenv(‘GEEKFLARE_API_KEY‘);

  // Create Guzzle client
  $client = new Client();

  try {

    // Send request
    $response = $client->request(‘POST‘, ‘https://api.mcngmarketing.com/loadtime‘, [
      ‘headers‘ => [
        ‘Authorization‘ => ‘Bearer ‘ . $apiKey   
      ],
      ‘json‘ => [
        ‘url‘ => $url
      ]
    ]);

    // Decode response    
    $data = json_decode($response->getBody(), true);

    // Return load time     
    return $data[‘data‘];

  } catch (Exception $e) {

    // Error handling
    return [
      ‘error‘ => $e->getMessage()  
    ];

  }

}


/**
 * Display load time form
 */
function displayForm() {

  echo ‘<form method="POST">‘;
  echo ‘<input name="url" placeholder="Enter URL">‘;
  echo ‘<button type="submit">Check load time</button>‘;
  echo ‘</form>‘;

}


/**
 * Display load time results 
 */
function displayResults($results) {

  if (isset($results[‘error‘])) {
    echo "<div style=‘color:red‘>{$results[‘error‘]}</div>";
  } else {
    echo "<div>DNS lookup: {$results[‘dns‘]}</div>"; 
    echo "<div>Connection: {$results[‘connect‘]}</div>";
    echo "<div>TTFB: {$results[‘ttfb‘]}</div>";  
    echo "<div>Total time: {$results[‘total‘]}</div>";
  }

}

After installing Guzzle, this provides a working load time checker:

Geekflare Load Time Checker

While basic, it shows a real-world example of:

  • Making API requests with Guzzle
  • Passing the API key for authentication
  • Handling JSON responses
  • Displaying load time results

You can expand on this foundation to create more robust applications.

Let‘s look at a few other Geekflare API endpoints you may find useful.

Additional Endpoints and Use Cases

The Geekflare API provides many endpoints beyond load time checks:

  • Broken link checker – Find broken links on a webpage. Helpful for monitoring your content.

  • DNS lookup – Lookup DNS records and test propagation. Useful for diagnosing DNS issues.

  • PageSpeed Insights – Check performance on mobile and desktop. Provides actionable suggestions for optimizations.

  • SSL tester – Verify certificate details and test hostname matching. Helps catch SSL misconfigurations.

  • Uptime monitoring – Get alerts when your website goes down. Critical for monitoring production sites.

And more!

The full list of endpoints is available in their API documentation.

Each endpoint follows a similar pattern of passing parameters and handling the JSON response.

For example, here is how to check broken links on a page:

$client = new Client();

$response = $client->request(‘POST‘, ‘https://api.mcngmarketing.com/brokenlinks‘, [
  ‘headers‘ => [
    ‘Authorization‘ => ‘Bearer ‘ . getenv(‘GEEKFLARE_API_KEY‘)
  ],
  ‘json‘ => [
    ‘url‘ => ‘https://www.example.com‘
  ]
]);

$data = json_decode($response->getBody(), true);

// Print each broken link  
foreach ($data[‘data‘] as $link) {
  echo $link[‘url‘] . ‘ is broken!‘;
}

The APIs are designed similarly so you can easily swap endpoints.

Some ideas for building on these APIs:

  • Scheduled CRON jobs that run checks and email reports
  • Log monitoring results to your own database
  • Trigger alerts for uptime failures or expiring SSL certificates
  • Create custom performance dashboards
  • Build monitoring as a service platform

The possibilities are endless!

Conclusion

The Geekflare API provides powerful website monitoring and optimization tools accessible right from PHP.

As we covered, you can easily leverage the API using standard skills:

  • PHP fundamentals
  • Composer for dependencies
  • Guzzle for requests
  • JSON handling
  • API key authentication

This opens the door to integrating Geekflare with your own applications.

Their API docs neatly organize all available endpoints. And the JSON responses provide structured data for parsing.

Common use cases include:

  • Reporting on website performance
  • Automated monitoring and alerting
  • Centralizing logs from multiple API endpoints
  • Building interactive web dashboards

While the examples used basic code, you can integrate the API into robust MVC frameworks like Laravel or Symfony.

Hopefully this guide provided a good overview of essential concepts for using the Geekflare API with PHP. The examples and code snippets serve as useful references for your projects.

You now have the foundation to start building awesome applications powered by their API!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.