Craig Craig - 1 year ago 60
PHP Question

Target specific files that include text in a particular directory?

I have the following php code below which is randomising the header images on page load.

function displayBackground() {
global $site;
global $dirimgpth;

$dir = 'uploads/product-images/' .$dirimgpth. '';
$cnt = 0;
$bgArray= array();

if ($handle = opendir($dir)) {

while (false !== ($entry = readdir($handle))) {

$pathToFile = $dir.$entry;
$bgArray[$cnt]= $pathToFile;
$cnt = $cnt+1;
$myRand = rand(0,($cnt-1));
$val = $bgArray[$myRand];




This all works fine which is great, but the directory I am getting the images from has several hundred image files containing thumbnails and large images.

I would like to change the code above to target the directory folder but only get image files with specific text of "-header.jpg" in the filename.

The directory folder contains files like the following:

  1. doors.jpg

  2. windows.jpg

  3. aluminium-thumb.jpg

  4. window-header.jpg

  5. conservatory-header.jpg

  6. tiled-thumb.jpg

  7. roof-header.jpg

The outcome I would like is so the random header only outputs images "4,5,7" from the above list.

Answer Source

If $entry is your file name you can check if it contains "-header" in name or not like this.

  while (false !== ($entry = readdir($handle))) {
   if (strpos($entry, '-header') !== false) {
     $pathToFile = $dir.$entry;
     // follow with your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download