开发者

List content of directory (php)

开发者 https://www.devze.com 2023-02-04 07:51 出处:网络
I have 开发者_开发问答a folder. I want to put every file in this folder into an array and afterwards I want to echo them all in an foreach loop.

I have 开发者_开发问答a folder. I want to put every file in this folder into an array and afterwards I want to echo them all in an foreach loop.

What's the best way to do this?

Thanks!


Scandir is what you're looking for http://php.net/manual/en/function.scandir.php

<?php
$dir    = '/tmp';
$files1 = scandir($dir);

print_r($files1);
?>

Or use combination of opendir and readdir http://php.net/manual/en/function.readdir.php


Doesn't get much easier than this

http://ca3.php.net/manual/en/function.scandir.php

Don't forget to filter out hidden and parent directories (they start with a dot) on linux.


An Alternative:

define('PATH', 'files/');

$filesArray = array();
$filesArray = glob(PATH . '*', GLOB_ONLYDIR);

This method allow you to specify/filter a by file type. E.G.,

define('PATH', 'files/');
define('FILE_TYPE', '.jpg');

$filesArray = array();
$filesArray = glob(PATH . '*' . FILE_TYPE, GLOB_ONLYDIR);

You can also get the FULL path name to the file by removing the parameter 'GLOB_ONLYDIR'


This works for files and folders in subfolders too. Return list of folders and list of files with their path.



    $dir = __DIR__; //work only for this current dir
    function listFolderContent($dir,$path=''){
        $r = array();
        $list = scandir($dir);
        foreach ($list as $item) {
            if($item!='.' && $item!='..'){
                if(is_file($path.$item)){
                    $r['files'][] = $path.$item;
                }elseif(is_dir($path.$item)){
                    $r['folders'][] = $path.$item;
                    $sub = listFolderContent($path.$item,$path.$item.'/');
                    if(isset($sub['files']) && count($sub['files'])>0)
                        $r['files'] = isset ($r['files'])?array_merge ($r['files'], $sub['files']):$sub['files'];
                    if(isset($sub['folders']) && count($sub['folders'])>0)
                        $r['folders'] = array_merge ($r['folders'], $sub['folders']);
                }
            }
        }
        return $r;
    }
    $list = listFolderContent($dir);
    var_dump($list['files']);
    var_dump($list['folders']);


Edit: dwich answer is better. I will leave this just for information.

readdir.

<?php

if ($handle = opendir('/path/to/dir')) {
    echo "Directory handle: $handle\n";
    echo "Files:\n";

    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Hope this helps.
—Alberto

0

精彩评论

暂无评论...
验证码 换一张
取 消