John Davidson

grep - PHP Get file which is older than 1 day and where filename starts with "a"

0 comments
Message:


So what I want to do is:


Delete a file:



  • If a filename in a directory starts with 'a' then check if it's older than 1 day.


OR



  • If a filename in a directory starts with 'b' then check if it's older than 1 week.


Example:


afilename.jpg (timestamp says the file is 2 days old) -> Delete / unlink.


What I tried so far:


<?php
// $files = preg_grep('~^a.*~', scandir("./uploads"));
// I want to combine line 1 & line 3 but I don't know how to do this.
$files = shell_exec('find ./uploads -mmin +1440');
$file = explode("\n",$files);
if(isset($file) && is_array($file))
{
foreach($file as $val)
{
// @unlink($val);
echo "found";
}
}
?>

I hope it is clear what I want to do.


Thanks in advance. :)



My Answer:
To achieve what you want, you can use the following PHP code:

php
$files = preg_grep('~^a.*~', scandir("./uploads"));
foreach($files as $file) {
$file_path = "./uploads/" . $file;
$file_time = filemtime($file_path);
$current_time = time();
$time_diff = $current_time - $file_time;

if ($time_diff > 86400) { // 1 day = 86400 seconds
unlink($file_path);
echo "Deleted file: $file\n";
}
}
?>


This code will scan the "uploads" directory for files starting with 'a', check if they are older than 1 day, and delete them if they meet the criteria. You can adjust the time difference check as needed for files starting with 'b' and older than 1 week.

Rate this post

5 of 5 based on 1015 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us