Auto delete all files after x-time
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);
}
}
}