Search for files beginning in "t_"
Posted: Sat Oct 04, 2008 9:51 am
I am using the code below to cycle through all files and subfolders within a particular directory. The results are placed in an array and then echo'd out. What I need to do is tweak this code so that it filters the items added to the list to only those whose filename begins with "t_". I then need the link the image to the matching filename in that same location that does not begin with "t_".
Any help is greatly appreciated! Thanks in advance!
Any help is greatly appreciated! Thanks in advance!
Code: Select all
<?php
// files to search for
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
// set to specific image if needed
// null will result in a random image
$img = null;
// path to the directory you want to scan
$directory = 'images/';
if (substr($directory,-1) != '/') {
$directory = $directory.'/';
}
// if img is set, show it
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $directory.$imageInfo['basename'] )) {
$img = $directory.$imageInfo['basename'];
}
}
// if img isnt set, grab a random
else {
//cycle through directory and subfolders
$it = new RecursiveDirectoryIterator("$directory");
foreach(new RecursiveIteratorIterator($it) as $file)
{
$file_info = pathinfo($file);
if (isset( $extList[ strtolower( $file_info['extension'] ) ] ) &&
strpos($file_info['basename'],"03")) {
$items[] = $file;
}
}
sort($items);
// get the random image
if (count($items) > 0) {
$imageNumber = rand(0,count($items));
//$imageNumber = time() % count($items);
//$img = $directory.$items[$imageNumber];
$img = $items[$imageNumber];
}
}
// if img isnt null, display it
if ($img!=null) {
$imageInfo = pathinfo($img);
//$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
//header ($contentType);
//readfile($img);
echo '<a href="' . $img . '"><img src="' . $img . '" alt="" /></a>';
}
// else, try to create one or give error
else {
/*if ( function_exists('imagecreate') ) {
//header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}*/
die("Unable to get image");
}
?>