Home > Backend Development > PHP Problem > How to delete files by time in PHP?

How to delete files by time in PHP?

Guanhui
Release: 2023-03-01 15:26:01
Original
3242 people have browsed it

How to delete files by time in PHP?

#How to delete files by time in PHP?

First use the function "opendir()" to read all files in the folder; then use the function "is_dir()" to filter out the folder; then use the function "filemtime()" to get the file creation time; finally delete it according to the creation time.

Code example

<?php
/*
 * 删除文件夹下$n分钟前创建的文件
 * @param $dir 要处理的目录,物理路径,结尾不加\
 * @param $n 过期时间,单位为分钟
 * @return void
 */
function del_file_by_ctime($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);
    }
}


//下面是调用的代码
//删除1天前的文件
$dir = realpath(&#39;./Upload/export&#39;);
del_file_by_ctime($dir, 24*60);
?>
Copy after login

Recommended tutorial: "PHP"

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

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template