Hi guys,
I modified randomFile php script into snippets..
The function is
- get random files on specified folder.
- get random files filtered by extension.
- get result filename only or filename and folder name.
I’m newbie for this. please check and need your suggestion. THankz
b4ndeng
<?php
// Snippets name : randomfile v.1
// Mod by : b4ndeng
//base Asset Dir
$basedir = $modx->config['rb_base_dir'];
$dirname = $basedir . $dir;
//$folder ; folder name
//$extenstions; file extension ex: jpg | gif
//$withfolder; result random including folder or just file only 'nofolder' and ''
function RandomFile($folder='', $extensions='.*',$withfolder='nofolder'){
// trimming folder
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
// check folder:
if (!is_dir($folder)){ die('invalid folder given!'); }
// create files array
$files = array();
// open directory
if ($dir = @opendir($folder)){
// go trough all files:
while($file = readdir($dir)){
if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){
// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}
if (count($files) == 0){
die('No files where found ');
}
// seed random function:
mt_srand((double)microtime()*1000000);
// get an random index:
$rand = mt_rand(0, count($files)-1);
// check again:
if (!isset($files[$rand])){
die('Array index was not found! ');
}
// return the random file:
if ($withfolder == 'nofolder'){
$folder = '';
}
return $folder . $files[$rand];
}
$randomFile = RandomFile($dirname,'jpg|png|gif');
print $randomFile;
?>
admin note: code tags added
Bali Web Design - www.babonmultimedia.com
"When my brain got bottleneck of code, get into the garden , drink cup a coffee and enjoy Sun shining and warm weather in tropical island"