forked from imabutahersiddik/CodeStore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_management.php
More file actions
60 lines (53 loc) · 1.59 KB
/
api_management.php
File metadata and controls
60 lines (53 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
class APIManagement {
private $pdo;
private $currentTime;
private $currentUser;
public function __construct($pdo) {
$this->pdo = $pdo;
$this->currentTime = '2025-06-14 12:47:29';
$this->currentUser = 'imabutahersiddik';
}
public function generateAPIKey() {
$apiKey = bin2hex(random_bytes(32));
$stmt = $this->pdo->prepare("
INSERT INTO api_keys
(user_id, api_key, created_at, last_used)
VALUES (?, ?, ?, NULL)
");
$stmt->execute([
$_SESSION['user_id'],
$apiKey,
$this->currentTime
]);
return $apiKey;
}
public function checkRateLimit($apiKey, $endpoint) {
$stmt = $this->pdo->prepare("
SELECT COUNT(*)
FROM api_requests
WHERE api_key = ?
AND endpoint = ?
AND created_at >= DATE_SUB(?, INTERVAL 1 HOUR)
");
$stmt->execute([$apiKey, $endpoint, $this->currentTime]);
$count = $stmt->fetchColumn();
// Limit: 1000 requests per hour
return $count < 1000;
}
public function logAPIRequest($apiKey, $endpoint, $response_code) {
$stmt = $this->pdo->prepare("
INSERT INTO api_requests
(api_key, endpoint, response_code, ip_address, created_at)
VALUES (?, ?, ?, ?, ?)
");
return $stmt->execute([
$apiKey,
$endpoint,
$response_code,
$_SERVER['REMOTE_ADDR'],
$this->currentTime
]);
}
}
?>