PHP code example to list all files in a directory

WBOY
Release: 2016-07-25 08:58:16
Original
1124 people have browsed it
This article introduces an example code that uses PHP to list all files in a directory for your reference.

List all files in the directory, the code is as follows:

<?php
$current_dir = 'E:/temp/';
$dir = opendir($current_dir);
echo "direcotry list:<ul>";
while(false !== ($file=readdir($dir))){
if($file != "." && $file != ".."){
echo "<li>$file</li>";
}
} //by bbs.it-home.org
echo "</ul>";
closedir($dir);
?>
Copy after login

If the directory and the website are in the same partition, you can also use $current_dir='/temp/'; directly.

The above is an example under Windows. Let’s look at a PHP example under Linux that lists all files in a directory. as follows: 1. Get the files in the directory, excluding subdirectories.

<?php
//获取某目录下所有文件、目录名(不包括子目录下文件、目录名)
    $handler = opendir($dir);
    while (($filename = readdir($handler)) !== false) {//务必使用!==,防止目录下出现类似文件名“0”等情况
        if ($filename != "." && $filename != "..") {
                $files[] = $filename ;
           }
       }
    }
    closedir($handler);
     
//打印所有文件名
foreach ($filens as $value) {
    echo $value."<br />";
}
?>
Copy after login

2. Get all files in the directory, including subdirectories.

<?php
function get_allfiles($path,&$files) {
    if(is_dir($path)){
        $dp = dir($path);
        while ($file = $dp ->read()){
            if($file !="." && $file !=".."){
                get_allfiles($path."/".$file, $files);
            }
        }
        $dp ->close();
    }
    if(is_file($path)){
        $files[] =  $path;
    }
} //edit bbs.it-home.org
   
function get_filenamesbydir($dir){
    $files =  array();
    get_allfiles($dir,$files);
    return $files;
}
   
$filenames = get_filenamesbydir("static/image/");
//打印所有文件名,包括路径
foreach ($filenames as $value) {
    echo $value."<br />";
}
?>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!