48

I am using WordPress. I have an image folder like mytheme/images/myimages.

I want to retrieve all the images name from the folder myimages

Please advice me, how can I get images name.

likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
Sksudip
  • 569
  • 2
  • 6
  • 9

12 Answers12

112

try this

$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");

foreach($images as $image)
{
  echo $image;
}
Cyril Jacquart
  • 2,632
  • 3
  • 25
  • 24
sharif2008
  • 2,716
  • 3
  • 20
  • 34
21

you can do it simply with PHP opendir function.

example:

$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
  if($file !== '.' && $file !== '..'){
    echo '<img src="pictures/'.$file.'" border="0" />';
  }
}
RavatSinh Sisodiya
  • 1,596
  • 1
  • 20
  • 42
zur4ik
  • 6,072
  • 9
  • 52
  • 78
14

When you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image

  $all_files = glob("mytheme/images/myimages/*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
          } else {
              continue;
          }
    }

If you do not want to check image type then you can use this code also

 $all_files = glob("mytheme/images/myimages/*.*");
 for ($i=0; $i<count($all_files); $i++)
 {
  $image_name = $all_files[$i];
  echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
 }

for more information

PHP Manual

Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43
4

Here is my some code

$dir          = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);

function Get_ImagesToFolder($dir){
    $ImagesArray = [];
    $file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];

    if (file_exists($dir) == false) {
        return ["Directory \'', $dir, '\' not found!"];
    } 
    else {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $file) {
            $file_type = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($file_type, $file_display) == true) {
                $ImagesArray[] = $file;
            }
        }
        return $ImagesArray;
    }
}
Ajay Kumar
  • 1,314
  • 12
  • 22
4

This answer is specific for WordPress:

$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );

$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';

$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();

foreach ( $image_paths as $image ) {
    $image_names[] = str_replace( $media_dir, '', $image );
    $image_urls[] = str_replace( $media_dir, $media_url, $image );
}

// --- You now have:

// $image_paths ... list of absolute file paths 
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg

// $image_urls ... list of absolute file URLs 
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg

// $image_names ... list of filenames only
// e.g. sample.jpg

Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:

From Uploads directory:

// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );

From Parent-Theme

// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );

From Child-Theme

// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
Philipp
  • 10,240
  • 8
  • 59
  • 71
3
$dir = "mytheme/images/myimages";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);

Very fast because you only scan the needed directory.

Lorenz
  • 2,179
  • 3
  • 19
  • 18
3
//path to the directory to search/scan
        $directory = "";
         //echo "$directory"
        //get all files in a directory. If any specific extension needed just have to put the .extension
        //$local = glob($directory . "*"); 
        $local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
        //print each file name
        echo "<ul>";

        foreach($local as $item)
        {
        echo '<li><a href="'.$item.'">'.$item.'</a></li>';
        }

        echo "</ul>";
alex
  • 63
  • 1
  • 7
2

Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:

$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);


if ($handle = opendir('/path/to/folder')) {

    while (false !== ($entry = readdir($handle))) {
        $files[] = $entry;
    }
    $images=preg_grep('/\.jpg$/i', $files);

    foreach($images as $image)
    {
    echo $image;
    }
    closedir($handle);
}
Nikita TSB
  • 440
  • 4
  • 11
  • 1
    Could you elaborate a little bit on your answer? – brodoll Nov 03 '15 at 18:05
  • check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this: '$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);' – Nikita TSB Nov 03 '15 at 18:08
  • please remove the starting quote. – Gogol Jun 22 '16 at 21:01
  • What does the `while (false !== (` part mean? I've seen it in a couple of answers, but it doesn't make sense to me, why are we looping through a false statement? – Studocwho Jan 03 '18 at 14:19
  • @Studocwho readdir function warning from php.net: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. – Nikita TSB Jan 24 '19 at 09:31
1
    <?php
   $galleryDir = 'gallery/';
   foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
   {echo "<a  href=\"$photo\">\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "</a>";}?>

UIkit php folder gallery https://webshelf.eu/en/php-folder-gallery/

EsternDust
  • 11
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – bitski Nov 10 '21 at 20:50
1
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
    echo '<img src="'.$image.'" /><br />';
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 26 '22 at 09:53
0
get all the images from a folder in php without database


$url='https://demo.com/Images/sliderimages/';
       $dir = "Images/sliderimages/";
        $file_display = array(
            'jpg',
            'jpeg',
            'png',
            'gif'
        );
        
        $data=array();
        
        if (file_exists($dir) == false) {
            $rss[]=array('imagePathName' =>"Directory  '$dir'  not found!");
            $msg=array('error'=>1,'images'=>$rss);
             echo json_encode($msg);
        } else {
            $dir_contents = scandir($dir);
        
            foreach ($dir_contents as $file) {
                @$file_type = strtolower(end(explode('.', $file)));
                // $file_type1 = pathinfo($file);
                // $file_type= $file_type1['extension'];
                
                if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
                   $data[]=array('imageName'=>$url.$file);
               
                   
                }
            }
            if(!empty($data)){
                $msg=array('error'=>0,'images'=>$data);
                echo json_encode($msg);
            }else{
                $rees[]=array('imagePathName' => 'No Image Found!');
                $msg=array('error'=>2,'images'=>$rees);
                echo json_encode($msg);
            }
        }
Anupam Verma
  • 49
  • 1
  • 3
-3

You can simply show your actual image directory(less secure). By just 2 line of code.

 $dir = base_url()."photos/";

echo"<a href=".$dir.">Photo Directory</a>";
Ajmal Tk
  • 153
  • 1
  • 4