PHP - Code to traverse a directory and get all the files(images)

前端 未结 10 2046
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 13:00

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 dis

10条回答
  •  醉酒成梦
    2021-01-27 13:19

    I would start off by creating a recursive function:

    function recurseDir ($dir) {
    
        // open the provided directory
        if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
    
            // we dont want the directory we are in or the parent directory
            if ($entry !== "." && $entry !== "..") {
    
                // recursively call the function, if we find a directory
                if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
    
                    recurseDir($dir.$entry);
                }
                else {  
    
                    // else we dont find a directory, in which case we have a file                          
                    // now we can output anything we want here for each file
                    // in your case we want to output all the images with the path under it
                    echo "";
                    echo "";
                }
            }
        }
    }
    

    The $dir param needs to be in the following format: "/path/" or "/path/to/files/"

    Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].

    So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.

提交回复
热议问题