php遍历目录与文件夹的多种方法详解
介绍几个php遍历目录的方法,可以遍历目录及目录中的文件,供大家参考
遍历目录或遍历目录下指定类型的文件,这是每一个童鞋在写程序的时候难免会用到的。PHP本身也提供了很多灰常有用的函数,正确地使用它们,不会有错滴。
下面就我个人学习过程中的一些总结,希望对想学PHP的童鞋有所帮助。
本函数可以列出指定目录下所有的文件(包括子目录下的)
复制代码 代码如下:
function getfiles($path){
foreach(scandir($path) as $afile)
{
if($afile=='.'||$afile=='..') continue;
if(is_dir($path.'/'.$afile))
{
getfiles($path.'/'.$afile);
} else {
echo $path.'/'.$afile.'
';
}
}
} //简单的demo,列出当前目录下所有的文件
getfiles(__DIR__);
scandir() 是返回指定目录下所有的文件和目录组成的数组,在PHP中,还提供了一个灰常强大的函数glob(),glob()有2个参数,至于第2个参数是可选的,稍后再讲。 直接来看,用glob()怎么遍历目录的。
可以看出,glob()返回的内容中已经过滤掉了'.'和'..',其中*表示遍历目录下所有文件。相应的,如果改为*.txt,则会遍历目录下所的txt文件。是不是很方便呢?它的方便之处可不止这一点,据元芳说,这里面还藏着一个天大的秘密,是什么呢?以后再说,有兴趣的话,可以给我留言交流。
复制代码 代码如下:
function getfiles($path){
foreach(glob($path) as $afile){
if(is_dir($afile))
{ getfiles($afile.'/*'); } else { echo $afile.'
'; }
}
} //简单的demo,列出当前目录下所有的文件
getfiles(__DIR__);0
既然说用 *.txt,就会遍历目录下所的txt文件,那如果我想让它同时遍历某几种格式的文件呢?怎么办?肯定有童鞋想到用数组了,然后很快的写出来替换进去{*.txt,*.jpg,*.zip,...},当然也很快地发现,程序返回false,什么都得不到。不要失望,这涉及到了刚才所说的第2个可选参数,这个参数是用来改变glob的行为的,具体都有些什么,可以查阅PHP手册,,这里不多讲,只说一个GLOB_BRACE,这是用来扩充 {a,b,c,...} 来匹配 'a','b' 或 'c',...的。用法如下:foreach(glob($path.'/{*.txt,*.jpg,*.zip,...}', GLOB_BRACE) as $fileName){...}
至于完整的遍历目录下所有的指定文件类型函数,我们可以看下面实例
遍历文件夹及子文件夹所有文件
复制代码 代码如下:
function traverse($path = '.') {
$current_dir = opendir($path); //opendir()返回一个目录句柄,失败返回false
while(($file = readdir($current_dir)) !== false) { //readdir()返回打开目录句柄中的一个条目
$sub_dir = $path . DIRECTORY_SEPARATOR . $file; //构建子目录路径
if($file == '.' || $file == '..') {
continue;
} else if(is_dir($sub_dir)) { //如果是目录,进行递归
echo 'Directory ' . $file . ':
';
traverse($sub_dir);
} else { //如果是文件,直接输出
echo 'File in Directory ' . $path . ': ' . $file . '
';
}
}
}
traverse('xxtt');
?>
一些常用的实例
复制代码 代码如下:
$dir="E:/video"; //这里输入其它路径
//PHP遍历文件夹下所有文件
$handle=opendir($dir.".");
echo "文件:
";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..") {
echo $file; //输出文件名
}
}
closedir($handle);
?>
用了这段代码遍历所有文件,帮我把所有文件名存为一个数组。
复制代码 代码如下:
$s=explode("/n",trim(`dir/b e://video`));
print_r($s);
?>
$dir="E:/video"; //这里输入其它路径
//PHP遍历文件夹下所有文件
$handle=opendir($dir.".");
echo "文件:
";
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..") {
$file=$file.','; //输出文件名
$file=explode(',',$file);
}
}
print_r($file);//输出的就是数组了
closedir($handle);
?>
$dir="."; //这里输入其它路径
//PHP遍历文件夹下所有文件
$handle=opendir($dir.".");
echo "文件:
";
//定义用于存储文件名的数组
$array_file = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..") {
$array_file[] = $file; //输出文件名
}
}
closedir($handle);
print_r("
");<br>print_r($array_file);<br>print_r("
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.
