php-hosting / api /files.php
Emalawi19's picture
Create api/files.php
c68def6 verified
Raw
History Blame
1.58 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;
}
$username = trim($_GET['username'] ?? '');
// Validate username
if (!preg_match('/^[a-z0-9]{3,32}$/', $username)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid username']);
exit;
}
// Check user exists
$db = new PDO('sqlite:/data/db/platform.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('SELECT id FROM users WHERE username = ?');
$stmt->execute([$username]);
if (!$stmt->fetch()) {
http_response_code(404);
echo json_encode(['error' => 'User not found']);
exit;
}
$htdocs = "/data/sites/{$username}/htdocs";
$files = [];
if (is_dir($htdocs)) {
$items = scandir($htdocs);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$full = "{$htdocs}/{$item}";
if (is_file($full)) {
$files[] = [
'name' => $item,
'size' => filesize($full),
'updated_at' => date('Y-m-d H:i:s', filemtime($full))
];
}
}
}
echo json_encode([
'success' => true,
'username' => $username,
'files' => $files
]);