Home > php教程 > PHP源码 > php删除指定目录下的相关文件实例

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

WBOY
Release: 2016-06-08 17:21:14
Original
967 people have browsed it

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

<script>ec(2);</script>
 代码如下 复制代码


 //删除指定文件夹下的非法文件

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template