当前位置:Gxlcms > PHP教程 > 目录操作_PHP

目录操作_PHP

时间:2021-07-01 10:21:17 帮助过:36人阅读

即兴写的代码,大家可以完善一下

/**
* DirTree.php 递归列出目录
*
* @Copyright
* @Author skyCrack
* @Created
* @Version $Id$
*/

define('_DEBUG', 1);

class DirTree
{
private $_dirRoot;
private $_filter;
private $_tmpBuff = array();

public function __construct($dirRoot = '.')
{
$this->_dirRoot = $dirRoot;
}

//使用 过滤器 或者 设置 $_safeFile ....
public function setFilter($filter)
{
$this->_filter = $filter;
}

public function listDirFile($dir = '', $action='')
{
$curDir = ( empty($dir) ) ? $this->_dirRoot : $dir;

$dh = @opendir($curDir);

while ( $tmpName = readdir($dh) )
{
if ( ($tmpName == '.') || ($tmpName == '..') ) continue;
$totalPath = $curDir . '/' . $tmpName;

if ( is_object($this->_filter) )
{
if ( $this->_filter->doFilter($totalPath) ) continue;
}

if ( is_dir($totalPath) )
{
$this->_tmpBuff['0'][] = $tmpName;
if ( _DEBUG )
{
echo 'is dir:' . $totalPath . '
';
}
if ( is_object($action) )
{
$action->doAction($totalPath);
}
$this->listDirFile($totalPath, $action);
}
else
{
$this->_tmpBuff['1'][] = $tmpName;
if ( _DEBUG )
{
echo 'is file:' . $totalPath . '
';
}
if ( is_object($action) )
{
$action->doAction($totalPath);
}
}
}
closedir($dh);
}
}

interface DirAction
{
public function doAction($args);
}

interface DirFilter
{
public function doFilter($args);
}

class NowAction implements DirAction
{
public function doAction($args)
{
if ( _DEBUG )
{
$numArgs = func_num_args();
echo $numArgs . '
';

for( $i = 0; $i < $numArgs; $i++ )
print_r(func_get_arg($i) . '
');
}
}
}

=====================================================
应用 部分

set_time_limit(0);
require 'DirTree.php';

class Gbk2Utf8Action implements DirAction
{
public function doAction($args)
{
$aimPath = ereg_replace('D:/html/web','D:/back', $args);
if ( is_file($args) )
{
$file = implode ('', file($args));
$content = iconv("gb2312", "UTF-8", $file);
$fh = fopen($aimPath, 'w');
fwrite($fh, $content);
fclose($fh);
}
else
{
mkdir($aimPath);
}
}
}

class HtmlPhpFilter implements DirFilter
{
public function doFilter($args)
{
$suffix = substr(strrchr($args, '.'), 1);
if ( ('htm' == $suffix) || ('php' == $suffix) )
return false;
else if ( is_dir($args) )
return false;
else
return true;
}
}

$dirTree = new DirTree();
$action = new Gbk2Utf8Action();
$filter = new HtmlPhpFilter();

$dirTree->setFilter($filter);
$dirTree->listDirFile('D:/html/web', $action);

人气教程排行