php-hosting / api /stats.php
Emalawi19's picture
Create api/stats.php
8cb6219 verified
Raw
History Blame Contribute Delete
2.45 kB
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
// Connect to SQLite
$db = new PDO('sqlite:/data/db/platform.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Total users
$totalUsers = $db->query('SELECT COUNT(*) FROM users')->fetchColumn();
// Disk usage of /data
$totalBytes = diskTotalSpace('/data');
$freeBytes = diskFreeSpace('/data');
$usedBytes = $totalBytes - $freeBytes;
// Per-user disk usage
$users = $db->query('SELECT username FROM users ORDER BY username')->fetchAll(PDO::FETCH_COLUMN);
$userStats = [];
foreach ($users as $username) {
$htdocs = "/data/sites/{$username}/htdocs";
$size = is_dir($htdocs) ? directorySize($htdocs) : 0;
$userStats[] = [
'username' => $username,
'size_bytes' => $size,
'size_human' => humanSize($size)
];
}
echo json_encode([
'success' => true,
'total_users' => (int)$totalUsers,
'disk' => [
'total_bytes' => $totalBytes,
'used_bytes' => $usedBytes,
'free_bytes' => $freeBytes,
'total_human' => humanSize($totalBytes),
'used_human' => humanSize($usedBytes),
'free_human' => humanSize($freeBytes),
'used_percent'=> $totalBytes > 0 ? round(($usedBytes / $totalBytes) * 100, 2) : 0
],
'users' => $userStats
]);
// ── Helpers ───────────────────────────────────────────────────────────────────
function directorySize(string $dir): int {
$size = 0;
$items = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
);
foreach ($items as $item) {
$size += $item->getSize();
}
return $size;
}
function humanSize(int $bytes): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$i = 0;
while ($bytes >= 1024 && $i < count($units) - 1) {
$bytes /= 1024;
$i++;
}
return round($bytes, 2) . ' ' . $units[$i];
}