Home  >  Article  >  Backend Development  >  php实现删除指定目录下相关文件的方法_PHP

php实现删除指定目录下相关文件的方法_PHP

WBOY
WBOYOriginal
2016-05-31 19:29:12788browse

本文实例讲述了php实现删除指定目录下相关文件的方法。分享给大家供大家参考。具体实现方法如下:

通常来说在php中删除文件最简单的方法就是直接使用unlink命令,而对于需要删除指定目录下的指定文件的情况,就需要遍历删除了。

具体实例代码如下:

代码如下:

 //删除指定文件夹下的非法文件
 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);

 希望本文所述对大家的PHP程序设计有所帮助。

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