Auto delete all files after x-time - php

How do you auto delete all files under a sub directory after x-time (let say after 24 hours) - without using a cronjob command from server or pl. How can you do this just using PHP code or by just visiting the page without clicking something and the command auto runs.

Response for last comment from my first answer. I'm going to write code sample, so I've created another answer instead of addition one more comment.
To remove files with custom extension you have to implement code:
<?php
$path = dirname(__FILE__).'/files';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400) { // 86400 = 60*60*24
if (preg_match('/\.txt$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>
Comment: 1. This example uses regular expression /\.txt$/i, which means, that only files with extension txt will be removed. '$' sign means, that filename has to be ended with string '.txt'. Flag 'i' indicates, that comparison will be case-insensitive. More about preg_match() function.
Besides you can use strripos() function to search files with certain extension. Here is code snippet:
<?php
$path = dirname(__FILE__).'/files';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400) { // 86400 = 60*60*24
if (strripos($file, '.txt') !== false) {
unlink($path.'/'.$file);
}
}
}
}
?>
Comment: This example seems more obvious. Result of strripos() also can be achieved with a combining of two functions: strrpos(strtolower($file), '.txt'), but, IMHO, it's a good rule to use less functions in your code to make it more readable and smaller. Please, read attentively warning on the page of strripos() function(return values block).
One more important notice: if you're using UNIX system, file removing could fail because of file permissions. You can check manual about chmod() function.
Good luck.

You can use PHP core functions filectime() and unlink() to check time of file creation and delete its file/files.
EDIT.
Code example:
if ($handle = opendir('/path/to/files')) {
while (false !== ($file = readdir($handle))) {
if (filectime($file)< (time()-86400)) { // 86400 = 60*60*24
unlink($file);
}
}
}

Well here we go, the PHP script that deletes the files that is X number of days old.
<?
$days = 1;
$dir = dirname ( __FILE__ );
$nofiles = 0;
if ($handle = opendir($dir)) {
while (( $file = readdir($handle)) !== false ) {
if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
continue;
}
if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
$nofiles++;
unlink($dir.'/'.$file);
}
}
closedir($handle);
echo "Total files deleted: $nofiles \n";
}
?>
Now paste this code and save it as a php file, upload it to the folder from where you want to delete the files. You can see at the beginning of this php code
$days = 1;
that sets the number of days, for example if you set it to 2 then files older than 2 days will be deleted. Basically this is what happens when you run the script, gets the current directory and reads the file entries, skips ‘.’ for current directory and further checks if there are any other directories,
if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) {
continue;
}
if the file entry is not a directory then it fetches the file modified time (last modified time) and compares, if it is number of days old
if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) {
$nofiles++;
unlink($dir.'/'.$file);
}
if the condition becomes true then it deletes the file with the help of unlink( ) php function. Finally closes the directory and exits. I have also added a counter to count the number of files being deleted, which will be displayed at the end of deletion process. So place the php file in the directory that needs the file deletion and execute it.
Hopefully that helps :)

I use shell AT command, it's like a cronjob though
php:
exec("echo rm /somedir/somefile.ext|at now +24 hours");

Here is another example that uses GLOB and it will delete any file
$files = glob('path/to/your/files/*');
foreach($files as $file) { // iterate files
// if file creation time is more than 5 minutes
if ((time() - filectime($file)) > 3600) { // 86400 = 60*60*24
unlink($file);
}
}
or if you want to exclude certain files
$files = preg_grep('#\.txt#', glob('/path/to/your/files/*'), PREG_GREP_INVERT);

After trying to use these examples, I hit a couple of issues:
The comparison operator should be greater than, not less than
filemtime returns the modified time. filectime is the time when a file's inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated, which may lead to unexpected results
I changed the example to use filemtime and fixed the comparison as follows:
<?php
$path = dirname(__FILE__).'/files';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filemtime($path.'/'.$file)) > 86400) { // 86400 = 60*60*24
if (preg_match('/\.txt$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>

function deleteCachedData($hours=24)
{
$files = glob(ROOTDIR.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'*.txt');
foreach($files as $file) {
if(is_file($file) && (time() - filectime($file)) > $hours*3600) {
unlink($file);
}
}
}

$path = 'folder/subfolder/';
/* foreach (glob($path.'.txt') as $file) { */
foreach (glob($path.'*') as $file) {
if(time() - filectime($file) > 86400){
unlink($file);
}
}

Related

The correct way to delete all images files in a folder older than 2 days in PHP

I want to delete all images those are older than 2 days or any number of days I want to add. I will add that file in cron job which will work on X no of days. I have used the below code for preforming this action.
<?php
$folderName='uploads';
if (file_exists($folderName)) {
foreach (new DirectoryIterator($folderName) as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
if ($fileInfo->isFile() && time() - $fileInfo->getCTime() >= 2*24*60*60) {
unlink($fileInfo->getRealPath());
}
}
}
?>
This code is not providing any error but Its not deleting images from the folder. I have tried many other codes from Internet but no success. So I need this small help.
you can try this code
<?php
$path = '/path/to/files/';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
//24 hours in a day * 3600 seconds per hour
if((time() - $filelastmodified) > 24*3600)
{
unlink($path . $file);
}
}
closedir($handle);
}
?>
You can call shell command from php like this,
find /data/haoqi_backup/db_code/db* -mtime +2 -exec rm {} \;

How to delete the next file in php

Let's say I have a folder containing 99tf.txt, 40.txt, 65.txt , in any order
If the current script var is 40.txt: I would like it to delete 65.txt (or the next file)
I was looking into something like that:
$file='40.txt';
if ($handle = opendir('./log/')) {
$entry= readdir($handle);
//move pointer to 40.txt
while ($file != $entry && $entry !== false) {
$entry = readdir($handle)
}
//go to the next file
$entry = readdir($handle)
if(is_file('./log/'.$entry)){
unlink('./log/'.$entry);
}
}
But I would like to avoid to go into a loop each time since there could be a lot of files in the folder.
So is there a way to change the $handle pointer to the '$file' directly and delete the next file?
If you don't mind using scandir, then this should work better for you.
$file = '40.txt';
$contents = scandir('./log/');
// Should already be sorted, but do again for safe measure
sort($contents);
// Make sure the file is in there.
if (false !== $index = array_search($file, $contents)) {
// If the file is at the end, do nothing.
if ($index !== count($contents)) {
// Remove the next index
unlink('./log/' . $contents[$index + 1]);
}
}
In regard to the order not mattering, you don't need to sort it. Worth noting however, is that your method, takes longer, but uses less memory, while this method is the reverse, much faster, but potentially more memory consumption.
<?php
$file = '40.txt';
$scan_folder = scandir('./log/');
$num_files = count($scan_folder);
if ($num_files > 1) {
$file_key = array_search($file, $scan_folder) +1;
unlink('./log/'.$file_key);
} else {
// here you will preserve only 1 file all others can be removed every time this script is executed
}
?>

How to echo out the contents of every text file that in a directory?

I have created a directory with some files in there:
index.php
one.txt
two.txt
three.txt
four.txt
In the index.php page, I am currently using this code to echo out all of the files within the directory:
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>
Now, if anyone views the index.php page, this is what they'll see:
one.txt two.txt three.txt four.txt
As you can see from the PHP code, index.php is blacklisted so it is not echoed out.
However, I would like to go a step further than this and echo out the contents of each text file rather than the filenames. With the new PHP code (that I need help with creating), whenever someone visits the index.php page, this is what they'll now see:
(Please ignore what is in the asterisks, they are not a part of the code, they just indicate what each text file contains)
Hello ** this is what the file **one.txt** contains **
ok ** this is what the file **two.txt** contains **
goodbye ** this is what the file **three.txt** contains **
text ** this is what the file **four.txt** contains **
Overall:
I would like to echo out the contents of every file in the directory (they are all text files) aside from index.php.
You could use file_get_contents to put the file into a string.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry " . file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
Furthermore, you could use PHP's glob function to filter only the .txt files out, that way you do not have to blacklist files if you're going to be adding more files to that directory that need ignored.
Here is how it would be done using the glob function.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename " . file_get_contents($filename) . "\n";
}
?>
This would print the contents of the files. You can do some workaround if the path is not the current path and writing some kind of boundary between the files contents.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
I hope this helps you.
Never reinvent the wheel. Use composer.
Require symfony/finder
use Symfony\Component\Finder\Finder;
class Foo
{
public function getTextFileContents($dir)
{
$finder = (new Finder())->files()->name('*.txt');
foreach ($finder->in($dir) as $file) {
$contents = $file->getContents();
// do something while file contents...
}
}
}
I would give a chance to some SPL filesystem iterators to accomplish such this task:
$dir = '/home/mydirectory';
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
$rdi = new \RegexIterator($rdi, '/\.txt$/i');
$iterator = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $file) {
echo 'Contents of the '.$file->getPathname().' is: ';
echo file_get_contents($file->getPathname());
}
This will recursively find & iterate all .txt files in given directory, including sub-directories.
Since each $file in iteration is a FilesystemIterator instance, you can use all related methods for additional controls like $file->isLink() (true for symbolic links), $file->isReadable() (false for unreadable files) etc..
If you don't want lookup sub-folders, just change the RecursiveDirectoryIterator in the second line from:
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
to:
$rdi = new \DirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
Hope it helps.
As #brock-b said, you could use glob to get the full list of files and file_get_contents to grab the contents:
$blacklist = array('index.php');
$files = glob('*.txt'); # could be *.* if needed
foreach ($files as $file) {
if (!in_array(basename($file), $blacklist)) {
echo file_get_contents($file);
}
}
Note: the blacklist wont be hit since you're seeking for *.txt files. Only useful when doing an *.* or *.php file search

PHP: How can I grab a single file from a directory without scanning entire directory?

I have a directory with 1.3 Million files that I need to move into a database. I just need to grab a single filename from the directory WITHOUT scanning the whole directory. It does not matter which file I grab as I will delete it when I am done with it and then move on to the next. Is this possible? All the examples I can find seem to scan the whole directory listing into an array. I only need to grab one at a time for processing... not 1.3 Million every time.
This should do it:
<?php
$h = opendir('./'); //Open the current directory
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..') { //Skips over . and ..
echo $entry; //Do whatever you need to do with the file
break; //Exit the loop so no more files are read
}
}
?>
readdir
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Just obtain the directories iterator and look for the first entry that is a file:
foreach(new DirectoryIterator('.') as $file)
{
if ($file->isFile()) {
echo $file, "\n";
break;
}
}
This also ensures that your code is executed on some other file-system behaviour than the one you expect.
See DirectoryIterator and SplFileInfo.
readdir will do the trick. Check the exampl on that page but instead of doing the readdir call in the loop, just do it once. You'll get the first file in the directory.
Note: you might get ".", "..", and other similar responses depending on the server, so you might want to at least loop until you get a valid file.
do you want return first directory OR first file? both? use this:
create function "pickfirst" with 2 argument (address and mode dir or file?)
function pickfirst($address,$file) { // $file=false >> pick first dir , $file=true >> pick first file
$h = opendir($address);
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..' && ( ($file==false && !is_file($address.$entry)) || ($file==true && is_file($address.$entry)) ) )
{ return $entry; break; }
} // end while
} // end function
if you want pick first directory in your address set $file to false and if you want pick first file in your address set $file to true.
good luck :)

PHP script to delete thousands of .jpg images?

My weak shared web host doesn't support cron or perl and I often need to delete thousands of .jpg images from certain folders. The images are uploaded from webcams. I'm wondering if there is a simple app out there that can find all .jpg images recursively and delete them.
I need to be able to target only images in the following date format : 2011-10-19_00-29-06.jpg ... and only images older than 48 hours.
Apache 2.2.20
DirectAdmin 1.39.2
MySQL 5.1.57
Php 5.2.17
#user427687, Do you mean all the picture format 2011***.jpg? if so, may be my code would work.
<?php
$path = dirname(__FILE__).'/filepath';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ((time()-filectime($path.'/'.$file)) < 86400*2) {
if (preg_match('/\2011(.*?).jpg$/i', $file)) {
unlink($path.'/'.$file);
}
if (preg_match('/\2011(.*?).jpeg$/i', $file)) {
unlink($path.'/'.$file);
}
}
}
}
?>
A simple naiive version:
$yesterday = date('Y-m-d', strtotime('yesterday')); // 2011-10-17
$day_before = date('Y-m-d', strtotime('2 days ago')); // 2011-10-16
$images = glob('*.jpg');
foreach($images as $img) {
if (strpos($img, $yesterday) === 0) || (strpos($img, $day_before) === 0)) {
continue;
}
unlink($img);
}
This will delete all files which are date-stamped 3 days or older, by checking if the file is date stamped yesterday or day-before-yesterday. But it will also delete all files created today.
A better version would be:
$images = glob("*.jpg");
foreach ($images as $img) {
$ctime = filectime($img);
if ($ctime < (time() - 86400 * 2)) {
unlink($img);
}
}
This version checks the actual last-modified time on the file, and deletes anything older than 48 hours. It will be slower, however, as the stat() call performed by filectime() will be a non-cheap call.
Something like this should get you started:
class MyRecursiveFilterIterator extends RecursiveFilterIterator {
const EXT = '.jpg';
public function accept() {
// code that checks the extension and the modified date
return $this->current()->getFilename() ...
}
}
$dirItr = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
// to iterate the list
foreach ($itr as $filePath => $fileInfo) {
echo $fileInfo->getFilename() . PHP_EOL;
}
or just with php:
<?php
$last_2_days_in_seconds = 3600 * 48;
foreach (glob("*.jpg") as $filename) {
if((time() - fileatime($filename)) > $last_2_days_in_seconds && preg_match('/^2011/', $filename)) unlink($filename);
}
?>

Categories