<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');
// Add debug parameter
$debug = isset($_GET['debug']) && $_GET['debug'] === '1';
// Directory where images are stored - try multiple paths
$possibleDirectories = [
'../images/',
'../../images/',
'./images/',
'../../../images/',
$_SERVER['DOCUMENT_ROOT'] . '/images/',
getcwd() . '/images/',
dirname(__FILE__) . '/../images/',
];
// Supported image extensions
$supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
$images = [];
$debugInfo = [];
$foundDirectory = null;
// Try to find the images directory
foreach ($possibleDirectories as $dir) {
$debugInfo[] = "Checking: " . realpath($dir) . " (exists: " . (is_dir($dir) ? 'yes' : 'no') . ")";
if (is_dir($dir)) {
$foundDirectory = $dir;
break;
}
}
if (!$foundDirectory) {
$response = [
'error' => 'Images directory not found',
'tried_paths' => $possibleDirectories,
'current_dir' => getcwd(),
'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'not set',
'debug_info' => $debugInfo
];
if ($debug) {
$response['all_files_in_current_dir'] = scandir('.');
$response['all_files_in_parent_dir'] = is_dir('..') ? scandir('..') : 'parent dir not accessible';
}
echo json_encode($response);
exit;
}
// Scan directory for image files
$files = scandir($foundDirectory);
$debugInfo[] = "Found directory: " . realpath($foundDirectory);
$debugInfo[] = "Files in directory: " . count($files);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$filePath = $foundDirectory . $file;
// Check if it's a file (not a subdirectory)
if (is_file($filePath)) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
// Check if it's a supported image format
if (in_array($extension, $supportedExtensions)) {
// Convert to web-accessible path
// Remove any ../ and make it relative to web root
$webPath = str_replace(['../'], '', $foundDirectory) . $file;
// Try different web path formats
$possibleWebPaths = [
$webPath,
'images/' . $file,
'/' . $webPath,
'../images/' . $file
];
// Use the first format for now
$images[] = $possibleWebPaths[0];
if ($debug) {
$debugInfo[] = "Added image: $file -> " . $possibleWebPaths[0];
}
}
}
}
// Sort images alphabetically
sort($images);
$response = [
'images' => $images,
'total_count' => count($images),
'directory_used' => realpath($foundDirectory),
'supported_formats' => $supportedExtensions
];
if ($debug) {
$response['debug_info'] = $debugInfo;
$response['possible_web_paths'] = isset($possibleWebPaths) ? $possibleWebPaths : [];
}
// Return just the images array for backward compatibility, unless debug is requested
echo json_encode($debug ? $response : $images);
?>