首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 實現隨機顯示圖片的三種方法總整理

     編輯:PHP 綜合知識

前言

網頁常見需求:隨機輪播廣告圖、隨機展示作品集縮圖、或隨機背景圖。PHP 配合 rand()、array_rand()、目錄掃描等功能,可輕鬆實現三種不同彈性的隨機圖片顯示方式。

方法一:固定圖片清單 + switch 隨機選擇

適合圖片數量固定、不需頻繁增減的情境(如首頁 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">

方法二:掃描目錄 + array_rand 隨機抽取

適合圖片會持續新增/刪除的資料夾(如使用者上傳相簿),無需手動維護清單。

<?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; ?>

方法三:獨立圖片輸出腳本(適合 <img src="random.php">)

將隨機邏輯封裝在單一 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/ 讀取敏感檔案。
  • 副檔名驗證: 僅允許圖片副檔名,避免輸出 PHP 腳本等執行檔。

小結

三種方法各有適用場景:固定清單最簡單、目錄掃描最彈性、獨立輸出腳本最易整合現有 HTML。實務上常搭配前端 JavaScript 做無縫輪播,或結合 CDN 快取隨機圖片 URL 以提升效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved