<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$type = $_GET['type'] ?? '';
if ($type === 'image') {
$dir = __DIR__ . "/images/";
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
} elseif ($type === 'audio') {
$dir = __DIR__ . "/audio/";
$allowedExtensions = ['mp3'];
} else {
echo json_encode(['success' => false, 'error' => 'Invalid type']);
exit;
}
if (!file_exists($dir)) {
echo json_encode(['success' => true, 'files' => []]);
exit;
}
$files = [];
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$extension = strtolower(pathinfo($item, PATHINFO_EXTENSION));
if (in_array($extension, $allowedExtensions)) {
$files[] = ($type === 'image' ? 'images/' : 'audio/') . $item;
}
}
// Sort files by newest first
usort($files, function($a, $b) use ($dir, $type) {
$prefix = $type === 'image' ? 'images/' : 'audio/';
$fileA = $dir . str_replace($prefix, '', $a);
$fileB = $dir . str_replace($prefix, '', $b);
return filemtime($fileB) - filemtime($fileA);
});
echo json_encode(['success' => true, 'files' => $files]);
?>