php-hosting / api /delete.php
Emalawi19's picture
Create api/delete.php
1c86072 verified
Raw
History Blame
3.43 kB
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(204);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
$username = trim($input['username'] ?? '');
$filepath = trim($input['filepath'] ?? ''); // empty = delete entire site
$deleteAll = (bool)($input['delete_all'] ?? false);
// 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";
// ── Delete entire site ────────────────────────────────────────────────────────
if ($deleteAll) {
$siteDir = "/data/sites/{$username}";
// Recursively delete the site directory
$deleted = deleteDirectory($siteDir);
if ($deleted) {
// Remove user and all files from database
$db->prepare('DELETE FROM files WHERE username = ?')->execute([$username]);
$db->prepare('DELETE FROM users WHERE username = ?')->execute([$username]);
echo json_encode([
'success' => true,
'message' => "Site {$username} deleted completely"
]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Failed to delete site directory']);
}
exit;
}
// ── Delete a single file ──────────────────────────────────────────────────────
$filepath = basename($filepath);
if (empty($filepath)) {
http_response_code(400);
echo json_encode(['error' => 'No filepath provided']);
exit;
}
$dest = "{$htdocs}/{$filepath}";
if (!file_exists($dest)) {
http_response_code(404);
echo json_encode(['error' => 'File not found']);
exit;
}
if (unlink($dest)) {
$db->prepare('DELETE FROM files WHERE username = ? AND filepath = ?')
->execute([$username, $filepath]);
echo json_encode([
'success' => true,
'message' => "File {$filepath} deleted"
]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Failed to delete file']);
}
// ── Helper: recursively delete a directory ────────────────────────────────────
function deleteDirectory(string $dir): bool {
if (!is_dir($dir)) return false;
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = "{$dir}/{$item}";
is_dir($path) ? deleteDirectory($path) : unlink($path);
}
return rmdir($dir);
}