PHP - 遍历目录并获取所有文件(图像)的代码

发布于 2024-09-17 03:50:22 字数 235 浏览 8 评论 0原文

我想编写一个页面,它将遍历指定的目录...并获取该目录中的所有文件...

在我的情况下,该目录将仅包含图像并显示图像及其链接...

类似这样

< img src="https://i.sstatic.net/ceiFy.png" alt="Example">

如何操作

ps 该目录不会是用户输入的..它将是同一目录总是...

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

紫﹏色ふ单纯 2024-09-24 04:42:02

您还可以尝试 glob 函数:

$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';

$images = glob($path . $pattern, GLOB_BRACE);

print_r($images);

You could also try the glob function:

$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';

$images = glob($path . $pattern, GLOB_BRACE);

print_r($images);
迷路的信 2024-09-24 04:36:34

我使用类似的东西:

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"; }

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"; }
筱果果 2024-09-24 04:31:02

您可以像其他人建议的那样检查目录中的每个文件,或者您可以使用 glob 根据扩展名识别文件。

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

冬天旳寂寞 2024-09-24 04:26:37
/**
*  function get files 
*  @param $path string = path to fine files in 
*  @param $accept array = array of extensions to accept 
*  @param currentLevel = 0, stopLevel = 0 
*  @return array of madmanFile objects, but you can modify it to 
*  return whatever suits your needs.  
*/

    public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){

            $path = trim($path);                    //trim whitespcae if any
            if(substr($path,-1)=='/'){$path = substr($path,0,-1);}  //cutoff the last "/" on path if provided
            $selectedFiles = array();
            try{
                    //ignore these files/folders
                    $ignoreRegexp = "/\.(T|t)rash/";
                    $ignore = array( 'cgi-bin', '.', '..', '.svn');
                    $dh = @opendir( $path );
                    //Loop through the directory
                    while( false !== ( $file = readdir( $dh ) ) ){
                            // Check that this file is not to be ignored
                            if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
                            $spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
                                    // Its a directory, so we need to keep reading down...
                                    if( is_dir( "$path/$file" ) ){
                                            //merge current selectFiles array with recursion return which is
                                            //another array of selectedFiles
                                            $selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
                                    } else{
                                            $info = pathinfo($file);
                                            if(in_array($info['extension'], $accept)){
                                                    $selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($

                                            }//end if in array
                                    }//end if/else is_dir
                            }
                    }//end while
                    closedir( $dh );
                    // Close the directory handle
            }catch (Exception $e){
                    echo 'Caught exception: ',  $e->getMessage(), "\n";
            }

            return $selectedFiles;
    }
/**
*  function get files 
*  @param $path string = path to fine files in 
*  @param $accept array = array of extensions to accept 
*  @param currentLevel = 0, stopLevel = 0 
*  @return array of madmanFile objects, but you can modify it to 
*  return whatever suits your needs.  
*/

    public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){

            $path = trim($path);                    //trim whitespcae if any
            if(substr($path,-1)=='/'){$path = substr($path,0,-1);}  //cutoff the last "/" on path if provided
            $selectedFiles = array();
            try{
                    //ignore these files/folders
                    $ignoreRegexp = "/\.(T|t)rash/";
                    $ignore = array( 'cgi-bin', '.', '..', '.svn');
                    $dh = @opendir( $path );
                    //Loop through the directory
                    while( false !== ( $file = readdir( $dh ) ) ){
                            // Check that this file is not to be ignored
                            if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
                            $spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
                                    // Its a directory, so we need to keep reading down...
                                    if( is_dir( "$path/$file" ) ){
                                            //merge current selectFiles array with recursion return which is
                                            //another array of selectedFiles
                                            $selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
                                    } else{
                                            $info = pathinfo($file);
                                            if(in_array($info['extension'], $accept)){
                                                    $selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($

                                            }//end if in array
                                    }//end if/else is_dir
                            }
                    }//end while
                    closedir( $dh );
                    // Close the directory handle
            }catch (Exception $e){
                    echo 'Caught exception: ',  $e->getMessage(), "\n";
            }

            return $selectedFiles;
    }
窗影残 2024-09-24 04:21:42

您可以使用 DirectoryIterator

try {
    $dir = './';
    /* @var $Item DirectoryIterator */
    foreach (new DirectoryIterator($dir) as $Item) {
        if($Item->isFile()) {
            echo $Item->getFilename() . "\n";
        }
    }
} catch (Exception $e) {
    echo 'No files Found!<br />';
}

您好,如果您想递归地传递目录, :
http://php.net/manual/en/class.recursivedirectoryiterator.php

Hi you can use DirectoryIterator

try {
    $dir = './';
    /* @var $Item DirectoryIterator */
    foreach (new DirectoryIterator($dir) as $Item) {
        if($Item->isFile()) {
            echo $Item->getFilename() . "\n";
        }
    }
} catch (Exception $e) {
    echo 'No files Found!<br />';
}

If you want to pass directories recursively:
http://php.net/manual/en/class.recursivedirectoryiterator.php

紫罗兰の梦幻 2024-09-24 04:15:23

您需要使用 scandir 函数来遍历列表目录中的文件。

You'll want to use the scandir function to walk the list of files in the directory.

梦年海沫深 2024-09-24 04:11:10
<?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 />";
  }
 }
} 
?>

来源:phpacademy.org

<?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

世俗缘 2024-09-24 04:07:20
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}

使用 readdir

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}

use readdir

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文