简体   繁体   中英

Displaying Images from a folder using PHP

I followed a few sites and have come to this:

<?php
  $imagesDir = base_url() . 'images/eventGallery/';

  $files = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

  for ($i = 0; $i < count($files); $i++) { 
    $num = $files[$i];
    echo '<img src="'.$num.'" alt="random image">'."&nbsp;&nbsp;";
  }

?>

It is not working as nothing is displaying! What am I doing wrong? There are two images in said directory, with ,jpg extension.

Thanks for any assistance!

  1. What does your base_url() returns? Do you have slash('/') between base url and images?
  2. case-sensitivity of glob is different on various systems, do your pictures have jpg or JPG or Jpg (etc) extensions?
  3. when creating img tags you must transform paths from file-system to web path (relative from web root)
  4. remove count from loop

This is working version of your code (altough I would rather use readdir :) ):

define('BASE_URL', dirname(__FILE__));

$imagesDir = BASE_URL . '/images/eventGallery/';

$files = glob($imagesDir . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);

$len=count($files);
for ($i = 0; $i < $len; $i++)
{ 
    $num = $files[$i];

    // transform from file system path to web path - assuming images is in the web root
    $num = substr($num, strlen(BASE_URL) ); 

    echo '<img src="'.$num.'" alt="random image">'."&nbsp;&nbsp;";
}

Just use PHP's built in readdir function

Reference: http://php.net/manual/en/function.readdir.php

   <?php
        if ($handle = opendir('.')) {
            while (false !== ($entry = readdir($handle))) {
                if ($entry != "." && $entry != "..") {
                    echo "$entry\n";
                }
            }
            closedir($handle);
        }
    ?>

i would probably do something like this:

foreach (glob('../_pics/about/'.'*.{jpg,jpeg,JPG,JPEG}', GLOB_BRACE) as $filename)
    {
            echo"$filename";
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM