62 lines
1.7 KiB
PHP
62 lines
1.7 KiB
PHP
<?php
|
|
/**
|
|
* Request Logger — Logs all API requests to MySQL
|
|
*/
|
|
|
|
require_once __DIR__ . '/Database.php';
|
|
|
|
class RequestLogger
|
|
{
|
|
/**
|
|
* Log an API request.
|
|
*/
|
|
public static function log(
|
|
string $endpoint,
|
|
string $method,
|
|
?array $requestBody = null,
|
|
int $responseCode = 200,
|
|
?string $error = null
|
|
): void {
|
|
if (!LOG_REQUESTS) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$db = Database::getInstance();
|
|
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
|
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
|
|
$body = $requestBody ? json_encode($requestBody) : null;
|
|
|
|
// Mask sensitive fields
|
|
if ($body) {
|
|
$body = self::maskSensitive($body);
|
|
}
|
|
|
|
$stmt = $db->prepare(
|
|
"INSERT INTO api_logs (endpoint, method, ip_address, user_agent, request_body, response_code, error, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
|
|
);
|
|
$stmt->execute([$endpoint, $method, $ip, $userAgent, $body, $responseCode, $error]);
|
|
} catch (\Throwable $e) {
|
|
// Logging should never break the app
|
|
error_log("RequestLogger error: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Mask sensitive fields in request body.
|
|
*/
|
|
private static function maskSensitive(string $body): string
|
|
{
|
|
$sensitive = ['app_key', 'password', 'otp', 'otp_code'];
|
|
foreach ($sensitive as $field) {
|
|
$body = preg_replace(
|
|
'/"' . $field . '"\s*:\s*"[^"]*"/',
|
|
'"' . $field . '":"***"',
|
|
$body
|
|
);
|
|
}
|
|
return $body;
|
|
}
|
|
}
|