Home >Backend Development >PHP Problem >How to automatically delete files in php

How to automatically delete files in php

藏色散人
藏色散人Original
2020-08-20 09:31:253583browse

php method to automatically delete files: first create a PHP sample file; then define a "del_file_by_time" method; then use the "self::del_file_by_time(WEB_ROOT.'/base64/',1);" method Just achieve automatic deletion.

How to automatically delete files in php

Recommended: "PHP Video Tutorial"

PHP automatically deletes all files or pictures before the specified time

When using PHP to upload files or images, sometimes some images are useless, or you may want to automatically clean up previous images or files after a while to save space. Delete all files before the specified time before each image upload.

Look at the code:

/*
 * 删除文件夹下$n分钟前创建的文件
 * @param $dir 要处理的目录,物理路径,结尾不加\
 * @param $n 过期时间,单位为分钟
 * @return void
 */
private function del_file_by_time($dir,$n)
{
    if(is_dir($dir)){
        if($dh=opendir($dir)){
            while (false !== ($file = readdir($dh))){
                if($file!="." && $file!=".."){
                    $fullpath=$dir."/".$file;
                    if(!is_dir($fullpath)){
                        $filedate=filemtime($fullpath);
                        $minutes=round((time()-$filedate)/60);
                        if($minutes>$n)
                            unlink($fullpath); //删除文件
                    }
                }
            }
        }
        closedir($dh);
    }
}

Call:

self::del_file_by_time(WEB_ROOT.'/upload/base64/',1);//删除一分钟以前所有文件

The above is the detailed content of How to automatically delete files in php. For more information, please follow other related articles on the PHP Chinese website!

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