Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Created September 30, 2017 13:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elhardoum/c686b0027b3923875f0704e3085b6cd6 to your computer and use it in GitHub Desktop.
Save elhardoum/c686b0027b3923875f0704e3085b6cd6 to your computer and use it in GitHub Desktop.
<?php
use Predis\Client as PredisClient;
include __DIR__ . '/vendor/autoload.php';
function redis() {
global $Redis;
if ( !isset($Redis) || !$Redis instanceof PredisClient ) {
$Redis = new PredisClient;
}
return $Redis;
}
function whatismyip() {
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = null;
return $ipaddress;
}
function send_json($resp, $status=200) {
header('Content-type: application/json; charset=utf-8');
if ( $status ) { // status code
http_response_code($status);
}
print json_encode($resp);
die;
}
$limit = [
'interval' => 5, // seconds
'num_requests' => 2, // number of requests allowed per interval
'user_ip' => whatismyip(), // getting the user IP.
];
$uid = "requests_count_{$limit['user_ip']}";
$logged = (int) redis()->get($uid);
if ( !$logged ) {
// first API request (or the count has expired)
$logged = 1;
// log the requests count to 1
redis()->set($uid, $logged);
// first time setting the key, expire the key at X seconds
redis()->expire($uid, $limit['interval']);
} else if ( $logged + 1 > $limit['num_requests'] ) {
// send them a notice to slow down
return send_json([
'success' => false,
'message' => 'Too many requests, please slow down or upgrade your API access plan.'
], 429);
} else {
// get the time-to-live integer
$ttl = redis()->ttl($uid);
// set the key
redis()->set($uid, $logged+1);
// expire the key at X seconds (ttl)
redis()->expire($uid, $ttl);
}
// Send the good response to the good users
send_json(['success' => true, 'data' => 'xyz']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment