php随机显示指定文件夹下的所有图片

发布时间:2020-03-08编辑:脚本学堂
php随机显示指定文件夹下的所有图片

随机显示指定文件夹下的所有图片。
 

复制代码 代码如下:
<?
# Init Array
$files = array();
# Get Folder
if($_GET['folder']) {
    $folder = $_GET['folder'];
} else {
    # Set Default Folder
    $folder = '/img/';
}
# Set Full Path
$path = $_SERVER['DOCUMENT_ROOT'] . '/' . $folder;
# Open Directory
if($handle = opendir($path)) {
    # Loop Through Directory
    while(false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if(substr($file, -3) == 'gif' || substr($file, -3) == 'png' || substr($file, -3) == 'jpg' || substr($file, -4) == 'jpeg') $files[count($files)] = $file;
                }
    }
}
# Close Handle
closedir($handle);
# Init Random
$rand = rand(0, count($files)-1);
# Check Header Type
# GIF
if(substr($files[$random], -3) == 'gif') header("Content-type: image/gif");
# JPEG
elseif(substr($files[$random], -3) == 'jpg') header("Content-type: image/jpeg");
elseif(substr($files[$random], -4) == 'jpeg') header("Content-type: image/jpeg");
# PNG
elseif(substr($files[$random],-3) == 'png') header("Content-type: image/png");
# Read File
readfile($path . '/' . $files[$random]);
?>