search
Homephp教程php手册PHP遍历某文件夹下的文件与文件夹名

opendir() 函数

opendir() 函数打开一个目录句柄,可由 closedir(),readdir() 和 rewinddir() 使用。

若成功,则该函数返回一个目录流,否则返回 false 以及一个 error。可以通过在函数名前加上 "@" 来隐藏 error 的输出。

语法为 opendir(path,context)。

  • 参数 path,必需。规定要打开的目录路径。
  • 参数 context,可选。规定目录句柄的环境。context 是可修改目录流的行为的一套选项。

下面是一个例子:

<?php
//打开 images 目录
$dir = opendir("bkjia");

//列出 images 目录中的文件
while (($file = readdir($dir)) !== false)
{
	echo "filename: " . $file . "<br />";
}
closedir($dir);
?> 

程序输出:

filename: .
filename: ..
filename: cat.gif
filename: dog.gif
filename: food
filename: horse.gif

这里把子目录和文件都输出了,现在只需要把子目录输出,可以用下面的函数实现:

<?php

function getSubDirs($dir) 
{
	$subdirs = array();
	if(!$dh = opendir($dir)) 
		return $subdirs;
	$i = 0;
	while ($f = readdir($dh)) 
	{
     	if($f =='.' || $f =='..') 
			continue;
		//如果只要子目录名, path = $f;
 		//$path = $dir.'/'.$f;  
		$path = $f;
		$subdirs[$i] = $path;
		$i++;
	}
	return $subdirs;
}

$arr = getSubDirs("tmp");
print_r($arr); 
?>

程序运行结果为:

Array ( [0] => Hello [1] => NowaMagic )

这次可以实现需求了。

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor