php-hosting / api /index.php
Emalawi19's picture
Create api/index.php
ee89f40 verified
Raw
History Blame Contribute Delete
2.21 kB
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
// ── Parse the route from the URL ──────────────────────────────────────────────
// Expected format: /api/register, /api/upload, /api/save etc.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path = rtrim($path, '/');
$parts = explode('/', $path);
// Last segment is the route e.g. "register" from "/api/register"
$route = end($parts);
$validRoutes = [
'register',
'upload',
'save',
'file',
'files',
'delete',
'stats',
'serve'
];
if (!in_array($route, $validRoutes)) {
http_response_code(404);
echo json_encode([
'error' => 'Unknown route',
'available' => array_map(fn($r) => "/api/{$r}", $validRoutes),
'docs' => [
'POST /api/register' => 'Create a new user site. Body: {"username":"alice"}',
'POST /api/upload' => 'Upload files. Form data: username + files[]',
'POST /api/save' => 'Save file from editor. Body: {"username":"alice","filepath":"index.php","content":"..."}',
'GET /api/file' => 'Get file content. Params: ?username=alice&filepath=index.php',
'GET /api/files' => 'List all files. Params: ?username=alice',
'POST /api/delete' => 'Delete file or site. Body: {"username":"alice","filepath":"index.php"} or {"username":"alice","delete_all":true}',
'GET /api/stats' => 'Disk usage and user count',
'GET /site/username/file' => 'View a user site e.g. /site/alice/index.php',
]
]);
exit;
}
// ── Route to the correct file ─────────────────────────────────────────────────
require_once __DIR__ . "/{$route}.php";