例如 限制 API 每秒仅允许请求一次
原来的API这样
1 2 3 |
$data = "Data Returned from API"; header('Content-Type: application/json'); die(json_encode($data)); |
加限制以后 这样
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)); |
以时间作为判断依据
这个适合小应用使用 其他规模的还是使用