1·项目部署

根目录 /www/demo.com

2·创建文件

/www/demo.com/i/random
/www/demo.com/i/random/random.php
/www/demo.com/i/random/default
/www/demo.com/i/random/xxxx

3·random.php

<?php
session_start(); // 开启会话

// 设置站点地址及图片文件夹
$weburl = 'https://demo.com/i/random/';
$paths = isset($_GET['path']) ? explode(',', $_GET['path']) : ['default'];

function getImagesFromDir($path) {
    $images = array();
    if ($img_dir = @opendir($path)) {
        while (false !== ($img_file = readdir($img_dir))) {
            if (preg_match("/(\.gif|\.jpg|\.png|\.webp)$/", $img_file)) {
                $images[] = $path . '/' . $img_file; // 添加路径
            }
        }
        closedir($img_dir);
    }
    return $images;
}

function getRandomFromArray($ar) {
    $lastImage = isset($_SESSION['last_image']) ? $_SESSION['last_image'] : null;

    do {
        $num = array_rand($ar);
        $newImage = $ar[$num];
    } while ($newImage === $lastImage && count($ar) > 1);

    $_SESSION['last_image'] = $newImage;
    return $newImage;
}

$imgList = array();
foreach ($paths as $path) {
    $imgList = array_merge($imgList, getImagesFromDir($path));
}

if (!empty($imgList)) {
    $img = getRandomFromArray($imgList);
    header("Location: " . $weburl . $img);
} else {
    echo "No images found in the directories.";
}
?>

4·使用

  • 使用默认default图库

    https://demo.com/i/random/index.php
  • 使用xxxx

    https://demo.com/i/random/index.php?path=xxxx

    示例

  • 示例1

    https://image.yishang.us.kg/i/random/index.php

    示例1

  • 示例2

    https://image.yishang.us.kg/i/random/index.php?path=man

    示例2

  • 示例3

    https://image.yishang.us.kg/i/random/index.php?path=coser,default

    示例3