<?php
header('Content-Type: application/xml; charset=UTF-8');
$dir = __DIR__ . '/uploads/'; // 圖片實體目錄(建議放在 Web 根目錄外,配合 rewrite 存取)
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
$baseUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/uploads/'; // 公開存取 URL 前綴
$xml = new XMLWriter();
$xml->openMemory();
$xml->setIndent(true);
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('photos');
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt, true)) continue;
$fullPath = $dir . $file;
if (!is_file($fullPath) || !is_readable($fullPath)) continue;
$stat = stat($fullPath);
$xml->startElement('item');
$xml->writeElement('url', $baseUrl . rawurlencode($file));
$xml->writeElement('filename', $file);
$xml->writeElement('size', $stat['size']);
$xml->writeElement('mtime', date('c', $stat['mtime'])); // ISO 8601
$xml->writeElement('width', 0); // 可選:getimagesize() 取得,大量檔案會慢
$xml->writeElement('height', 0);
$xml->endElement(); // item
}
closedir($dh);
$xml->endElement(); // photos
$xml->endDocument();
echo $xml->outputMemory();
?page=1&limit=50 參數分批輸出。若需標籤、相簿分類、權限控制,建議資料庫存儲圖片元資料(路徑、標題、標籤、上傳者、建立時間),XML/JSON API 僅查詢資料庫生成,不再掃描檔案系統。
Options Indexes(防止目錄列表洩露)。getimagesize() 確認為真實圖片、重新命名(UUID + 副檔名)、移除 EXIF 敏感資訊。X-Sendfile / X-Accel-Redirect (Nginx) 或 PHP 讀檔輸出做權限控管。