php遍历一个文件夹下的所有目录及文件 不指定

jed , 2010-9-25 11:46 , 代码编程 , 评论(0) , 阅读(2929) , Via 本站原创 | |
在面试中我们经常遇到这个题目:php遍历一个文件夹下的所有文件和子文件夹。

这个题目有好多种解决方法。但大致思路都一样。采用递归。


$path = './filepath';
function getfiles($path)
{
if(!is_dir($path)) return;
$handle = opendir($path);
while( false !== ($file = readdir($handle)))
{
if($file != '.' && $file!='..')
{
$path2= $path.'/'.$file;
if(is_dir($path2))
{
echo '
';
echo $file;
getfiles($path2);
}else
{
echo '
';
echo $file;
}
}
}
}

print_r( getfiles($path));

echo '



-------------------------------------------
';

function getdir($path)
{
if(!is_dir($path)) return;
$handle = dir($path);
while($file=$handle->read())
{
if($file!='.' && $file!='..')
{
$path2 = $path.'/'.$file;
if(is_dir($path2))
{
echo $file.”\t”;
getdir($path2);
}else
{
echo $file.'
';
}
}
}
}
getdir($path);

echo '



------------------------------------------------
';

function get_dir_scandir($path){

$tree = array();
foreach(scandir($path) as $single){
if($single!='.' && $single!='..')
{
$path2 = $path.'/'.$single;
if(is_dir($path2))
{
echo $single.”
\r\n”;
get_dir_scandir($path2);
}else
{
echo $single.”
\r\n”;
}
}
}
}
get_dir_scandir($path);

echo '
--------------------------------------------------
';

function get_dir_glob(){
$tree = array();
foreach(glob('./curl/*') as $single){
echo $single.”
\r\n”;
}
}
get_dir_glob();

echo '
------------------------------------------------------
';
function myscandir($path)
{
if(!is_dir($path)) return;
foreach(scandir($path) as $file)
{
if($file!='.' && $file!='..')
{
$path2= $path.'/'.$file;
if(is_dir($path2))
{
echo $file;
myscandir($path2);
}else
{
echo $file.'
';
}
}
}
}

myscandir($path);

echo '
-------------------------------------------
';

function myglob($path)
{
$path_pattern = $path.'/*';
foreach(glob($path_pattern) as $file)
{
if(is_dir($file))
{
echo $file;
myscandir($file);
}else
{
echo $file.'
';
}
}
}

myglob($path);



发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]