<?php
// serve_image.php
// Secure image streaming for passport photos

// Validate required parameters
if (!isset($_GET['file']) || !isset($_GET['loc'])) {
    http_response_code(400);
    echo "Missing parameters.";
    exit;
}

$file = basename($_GET['file']); // prevents directory traversal
$dir  = $_GET['loc'];

// Normalize directory path
$dir = rtrim($dir, "/\\");

// Construct full path
$fullPath = $dir . DIRECTORY_SEPARATOR . $file;

// Verify file exists
if (!file_exists($fullPath)) {
    http_response_code(404);
    echo "Image not found.";
    exit;
}

// Determine file MIME type
$mime = mime_content_type($fullPath);

// Only allow image types
$allowed = ['image/jpeg', 'image/png', 'image/gif'];

if (!in_array($mime, $allowed)) {
    http_response_code(403);
    echo "Invalid image type.";
    exit;
}

// Output image
header("Content-Type: $mime");
header("Content-Length: " . filesize($fullPath));

// Prevent caching (optional)
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");

readfile($fullPath);
exit;
?>
