Easy Rate Limit in PHP using Simple Strategy – An API Example


Nowadays the web-based APIs are popular. Many large websites provide APIs such as Facebook, Twitter. The return value is often encoded using JSON format. To limit the user from overusing the APIs. A Rate-Limit restriction is usually set and IP is recorded for each API (Application Programming Interface) call.

In PHP, you can accomplish the similar tasks by using very simple strategy. I’ll give you an example.

1
2
3
  $data = "Data Returned from API";
  header('Content-Type: application/json');
  die(json_encode($data)); 
  $data = "Data Returned from API";
  header('Content-Type: application/json');
  die(json_encode($data)); 

Now we can use these 3 lines of PHP code to push the encoded-JSON data to the browser. If we want to limit the usage say 1 second per call (if the API requires intensive server computation power), then we can record the _LAST_CALL time so it becomes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  session_start();
  if (isset($_SESSION['LAST_CALL'])) {
    $last = strtotime($_SESSION['LAST_CALL']);
    $curr = strtotime(date("Y-m-d h:i:s"));
    $sec =  abs($last - $curr);
    if ($sec <= 1) {
      $data = 'Rate Limit Exceeded';  // rate limit
      header('Content-Type: application/json');
      die (json_encode($data));        
    }
  }
  $_SESSION['LAST_CALL'] = date("Y-m-d h:i:s");
 
  // normal usage
  $data = "Data Returned from API";
  header('Content-Type: application/json');
  die(json_encode($data)); 
  session_start();
  if (isset($_SESSION['LAST_CALL'])) {
    $last = strtotime($_SESSION['LAST_CALL']);
    $curr = strtotime(date("Y-m-d h:i:s"));
    $sec =  abs($last - $curr);
    if ($sec <= 1) {
      $data = 'Rate Limit Exceeded';  // rate limit
      header('Content-Type: application/json');
      die (json_encode($data));        
    }
  }
  $_SESSION['LAST_CALL'] = date("Y-m-d h:i:s");

  // normal usage
  $data = "Data Returned from API";
  header('Content-Type: application/json');
  die(json_encode($data)); 

Put above code in a separate .PHP file and remember to use it at your API page (ensure it is placed at the very begining of source code because it needs to initialize the session by session_start() function). The LAST_CALL session variable is employed and the check is imposed before the actual API is called. In this way, we only allow users to call the API 1 time per second maximum.

1
require_once('rate.php');
require_once('rate.php');

--EOF (The Ultimate Computing & Technology Blog) --

GD Star Rating
loading...
353 words
Last Post: Escape Linux Command to Prevent Security Holes From PHP shell_exec Function
Next Post: The Fun Linux Utility - RIG - Random Identity Generator - The Online Tool and API

The Permanent URL is: Easy Rate Limit in PHP using Simple Strategy – An API Example

7 Comments

  1. Mulder
  2. Danton
  3. Paolo
  4. Luis

Leave a Reply