PHP - Code to traverse a directory and get all the

2020-05-02 12:47发布

i want to write a page that will traverse a specified directory.... and get all the files in that directory...

in my case the directory will only contain images and display the images with their links...

something like this

Example

How to Do it

p.s. the directory will not be user input.. it will be same directory always...

10条回答
ら.Afraid
2楼-- · 2020-05-02 13:31

You could as others have suggested check every file in the dir, or you could use glob to identify files based on extension.

查看更多
地球回转人心会变
3楼-- · 2020-05-02 13:32

I use something along the lines of:

if ($dir = dir('images'))
{       
    while(false !== ($file = $dir->read()))
    {
        if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
        {
            // do stuff with the images
        }
    }
}
else { echo "Could not open directory"; }
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-05-02 13:34
<?php 
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
 while(($file = readdir($opendir))!= FALSE ){
  if($file!="." && $file!= ".."){
   echo "<img src='$dir/$file' width='80' height='90'><br />";
  }
 }
} 
?>

source: phpacademy.org

查看更多
聊天终结者
5楼-- · 2020-05-02 13:35
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}

For further reference :http://php.net/manual/en/function.opendir.php

查看更多
登录 后发表回答