首页 > php代码 > php删除指定目录下的相关文件实例

php删除指定目录下的相关文件实例

在php中删除文件最简单的办法直接使用unlink命令,但本文章介绍的是需要删除指定目录下的指定文件,所以我需要遍历删除了,具体看这个例子。

<?php
//删除指定文件夹下的非法文件
function my_del($dir)
{
if(is_dir($dir)){
    //打开指定文件夹
    if($handle = opendir($dir))
    {
        while(false !== ($file = readdir($handle)))
        {
            if($file !== '.' && $file !== '..')
             {
                    my_del($dir.'/'.$file);
             }
        }
        $res = closedir($handle);
    }
}else{
    //删掉除图片意外的所有文件
    $avatararr = array('180x180.jpg', '30x30.jpg', '45x45.jpg', '90x90.jpg');
    $ex = explode('/', $dir);
    $endex = end($ex);
    if((strripos($endex,'.jpg') === false) || (substr($endex, -4) != '.jpg')){
                //按名称过滤
            @unlink($dir);
    } else {
                //按文件实质内容过滤
            $info = @getimagesize($dir);
            if(!$info || $info[2] !=2) {
                    @unlink($dir);
            }
    }
}
}
$dir='D:/xampp/htdocs/www/avatar001/12/47/';
my_del($dir);


文章网址:http://www.phprm.com/code/67929.html

随意转载^^但请附上教程地址。

标签:substr explode opendir

相关文章

发表留言