PHP随机显示图片示例
用于随机显示图片的PHP代码,可自行改编成函数。
<?php
/**
* Filename : randomimg.php
* Usage:
* <img src="randomimg.php" />
* <img src="randomimg.php?folder=pic" />
*/
define('WORK_ROOT', dirname(__FILE__));
if(@$_GET['folder']){
$folder=$_GET['folder'];
} else {
$folder='pic';
}
$path = WORK_ROOT . '/' . $folder;
$files=array();
if ($dir = opendir($path)){
while (($file = readdir($dir)) !== false){
if(preg_match('/.gif$|.jpg$|.png$/',$file)){
//echo "filename: " . $file . ",
";
$files[count($files)] = $file;
}
}
closedir($dir);
}
//echo var_dump($files);
$random=rand(0,count($files)-1);
//echo $files[$random];
if(substr($files[$random],-3)=='gif'){
header("Content-type: image/gif");
}else if(substr($files[$random],-3)=='jpg'){
header("Content-type: image/jpeg");
}else if(substr($files[$random],-3)=='png'){
header("Content-type: image/png");
}
readfile("$path/$files[$random]");
Try It Yourself: https://liaosnet.com/tiy/tiy_randompic.php
注:由于每次均需要对目录进行操作,效率并不高,建议仅用于了解随机方法。