我有一个文件夹,里面有很多文件。我的目标是根据创建或修改日期按年备份文件,在备份文件后,我还想删除这些文件。
实际上,我的服务器包含20 of大小的pdf文件,我想备份这些文件,但应该有文件夹年份。但我不知道如何做到这一点。
$dir_path = "/pdfs/";
$pdf_arr = scandir($dir_path);
foreach($pdf_arr as $file) {
if($file ! == '.' && $file ! == '..') {
print_r($file);
}
}发布于 2019-10-05 20:49:56
// year and month wise backup
public function getLastModifiedFiles() {
$source = public_path("pdfs");
$destination = public_path("destination");
$smallest_time=INF;
$oldest_file='';
if ($handle = opendir($source)) {
while (false !== ($file = readdir($handle))) {
if($file !== '.' && $file !== '..') {
$time = filemtime($source.'/'.$file);
$mm = date('m', $time);
$yr = date('Y', $time);
\File::isDirectory($destination.'/'.$yr."/$mm") or \File::makeDirectory($destination.'/'.$yr."/$mm", 0777, true, true);
$moveFile="$destination/$yr/$mm/$file";
//dd($source.'/'.$file);
if(!is_dir($source.'/'.$file)) {
if (copy($source.'/'.$file, $moveFile))
{
unlink($source.'/'.$file);
}
}
}
}
closedir($handle);
}
}发布于 2019-10-19 03:35:33
在我看来,这将是满足您需求的最佳解决方案:
<?php
// Constans to Define
$active_dir = "pdfs/"; // Directory where your files are stored * WITH ENDING "/"
$backup_dir = "pdfs_backup/"; // Directory where the files should be moved to backup * WITH ENDING "/"
$backup_time_str = "Y"; // "Y" will backup in yearly folder structure (ex 2019), "Y-m" will backup in monthly folder (ex 2019-01), "Y-m-d" will back up in daily folder (ex 2019-01-05)
$min_file_age = time()-(3600*24*365); // only BackUp files older than actual time minus seconds (In this Case 1 Year)
// Start BackUp
backup_files_by_time($active_dir,$backup_dir,$min_file_age,$backup_time_str);
// BackUp Function
function backup_files_by_time($active_dir,$backup_dir,$min_file_age,$backup_time_str="Y") {
$pdf_arr = scandir($active_dir);
foreach($pdf_arr as $file) {
if(file_exists($active_dir.$file)) {
$filetime = filemtime($active_dir.$file);
// File is supposed to be backuped
if ($filetime<$min_file_age) {
// Create Folder if not exists
if (!is_dir($backup_dir.date($backup_time_str,$filetime))) {mkdir($backup_dir.date($backup_time_str,$filetime));}
// Moving File to Backupfolder
rename($active_dir.$file,$backup_dir.date($backup_time_str,$filetime)."/".$file);
}
}
}
}
?>发布于 2019-10-22 16:26:21
我建议使用Symfony Finder组件,它非常强大:
$finder = new Finder();
$finder->files()
->in('/pdfs/')
->date('>= 2018-01-01');
foreach($finder as $files) {
// whatever you want to do
}https://stackoverflow.com/questions/58246642
复制相似问题