PHP Classes

File: demo_APIKey.php

Recommend this page to a friend!
  Classes of Ray Paseur   Lightweight PHP API Key Authentication   demo_APIKey.php   Download  
File: demo_APIKey.php
Role: Example script
Content type: text/plain
Description: Demonstration Script
Class: Lightweight PHP API Key Authentication
Store and validate user API keys in files
Author: By
Last change:
Date: 5 years ago
Size: 1,352 bytes
 

Contents

Class file image Download
<?php // demo/classes/demo_APIKey.php
/**
 * Demonstrate Classes to Generate / Validate an API Key PHP7+
 *
 * https://www.phpclasses.org/recommend/854-A-random-API-key-generator-to-server-as-access-restriction-to-AP.html
 */
error_reporting(E_ALL);

require_once(
'class_APIKey.php');
require_once(
'class_APIKeyValidation.php');
require_once(
'class_APIKeyException.php');

echo
'<pre>';


// Show how to use the class with Success to validate the key
$apikey = '3c98ea3c99806fde3aa810c9f0f56e0d'; // Came from URL or other request data
try {
   
$name = APIKeyValidation::validate($apikey);
    echo
PHP_EOL . "API Key $apikey belongs to $name";
}
catch(
APIKeyException $e) {
    echo
PHP_EOL . $e->getMessage();
    echo
PHP_EOL . $e->getCode() . " can be used as the HTTP code";
    echo
PHP_EOL;
}


// Show how to use the class with Failure to validate the key
$apikey = 'This-Bogus-API-Key';
try {
   
$name = APIKeyValidation::validate($apikey);
    echo
PHP_EOL . "API Key $apikey belongs to $name";
}
catch(
APIKeyException $e) {
    echo
PHP_EOL . $e->getMessage();
    echo
PHP_EOL . $e->getCode() . " can be used as the HTTP code";
    echo
PHP_EOL;
}


// Show how to generate a new API key
$new = APIKeyValidation::storeKey('New-User');
echo
PHP_EOL . "Look for '$new' in this list:";
echo
PHP_EOL;
readfile( APIKeyValidation::APIKEYFILE );