Home  >  Article  >  Backend Development  >  PHP traverses files and folder names in a folder_PHP tutorial

PHP traverses files and folder names in a folder_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:17944browse

opendir() function

The opendir() function opens a directory handle and can be used by closedir(), readdir() and rewinddir().

If successful, this function returns a directory stream, otherwise it returns false and an error. You can hide error output by prepending "@" to the function name.

The syntax is opendir(path,context).

  • Parameter path, required. Specifies the directory path to be opened.
  • Parameter context, optional. Specifies the environment for directory handles. context is a set of options that modify the behavior of the directory stream.

Here is an example:

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

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

Program output:

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

Both subdirectories and files are output here. Now you only need to output the subdirectory, which can be achieved by using the following function:

<?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); 
?>

The result of running the program is:

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

This time the requirement can be realized.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752518.htmlTechArticleopendir() function opendir() function opens a directory handle, which can be used by closedir(), readdir() and rewinddir( ) use. If successful, the function returns a directory stream, otherwise it returns fal...
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