Wednesday, July 7, 2010

Display random image


[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]);
[/PHP]

No comments:

Post a Comment