網頁常見需求:隨機輪播廣告圖、隨機展示作品集縮圖、或隨機背景圖。PHP 配合 rand()、array_rand()、目錄掃描等功能,可輕鬆實現三種不同彈性的隨機圖片顯示方式。
適合圖片數量固定、不需頻繁增減的情境(如首頁 Banner 輪播 4 張固定圖)。
<?php
// 1. 設定隨機種子(PHP 4.2+ 可省略,內建自動播種)
srand((double)microtime() * 1000000);
// 2. 產生 1~4 隨機數
$num = rand(1, 4);
// 3. 對應圖片路徑
switch ($num) {
case 1: $image_file = '/images/banner1.jpg'; break;
case 2: $image_file = '/images/banner2.jpg'; break;
case 3: $image_file = '/images/banner3.jpg'; break;
case 4: $image_file = '/images/banner4.jpg'; break;
}
?>
<img src="<?php echo $image_file; ?>" alt="隨機 Banner">
適合圖片會持續新增/刪除的資料夾(如使用者上傳相簿),無需手動維護清單。
<?php
$dir = __DIR__ . '/uploads/'; // 圖片資料夾絕對路徑
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$files = [];
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $allowedExt) && is_file($dir . $file)) {
$files[] = $file;
}
}
closedir($handle);
}
if ($files) {
$randomFile = $files[array_rand($files)];
$imgUrl = '/uploads/' . $randomFile; // 相對網址路徑
}
?>
<?php if (isset($imgUrl)): ?>
<img src="<?php echo $imgUrl; ?>" alt="隨機相簿圖">
<?php endif; ?>
將隨機邏輯封裝在單一 PHP 檔,直接輸出圖片二進位內容,HTML 只需 <img src="random.php"> 即可,支援資料夾參數切換。
random.php
<?php
// 參數:?folder=images2/ 指定子資料夾,預設 /images/
$folder = isset($_GET['folder']) ? $_GET['folder'] : '/images/';
$basePath = $_SERVER['DOCUMENT_ROOT'] . $folder;
$files = [];
if ($handle = opendir($basePath)) {
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$ext = strtolower(substr($file, -3));
if (in_array($ext, ['gif', 'jpg', 'png'])) {
$files[] = $file;
}
}
closedir($handle);
}
if ($files) {
$random = $files[array_rand($files)];
$filePath = $basePath . $random;
// 依副檔名送出正確 Content-Type
$ext = strtolower(pathinfo($random, PATHINFO_EXTENSION));
$mime = ['gif'=>'image/gif', 'jpg'=>'image/jpeg', 'jpeg'=>'image/jpeg', 'png'=>'image/png', 'webp'=>'image/webp'];
header('Content-Type: ' . ($mime[$ext] ?? 'application/octet-stream'));
readfile($filePath);
exit;
}
// 找不到圖片時回傳 1x1 透明 gif
header('Content-Type: image/gif');
echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
?>
HTML 使用方式:
<!-- 預設資料夾 -->
<img src="random.php" alt="隨機圖">
<!-- 指定子資料夾 -->
<img src="random.php?folder=/uploads/banners/" alt="隨機 Banner">
$files 陣列(如用 APCu、Redis 或靜態檔案快取 5-10 分鐘)。folder 參數務必做路徑正規化與白名單驗證,避免 ?folder=../../etc/ 讀取敏感檔案。三種方法各有適用場景:固定清單最簡單、目錄掃描最彈性、獨立輸出腳本最易整合現有 HTML。實務上常搭配前端 JavaScript 做無縫輪播,或結合 CDN 快取隨機圖片 URL 以提升效能。