To delete files older than 1 hour in PHP, you can use the combination of filemtime() function and unlink() function. Here’s an example code:
<?php
$directory = '/path/to/directory/'; // Replace with your directory path
// Get the current timestamp and subtract 1 hour (3600 seconds)
$threshold = time() - 3600;
// Open the directory
$handle = opendir($directory);
// Loop through each file in the directory
while (false !== ($file = readdir($handle))) {
// Check if the file is not a directory and its modification time is older than the threshold
if (!is_dir($directory . $file) && filemtime($directory . $file) < $threshold) {
// Delete the file
unlink($directory . $file);
}
}
// Close the directory handle
closedir($handle);
?>
In the above code, replace /path/to/directory/
with the actual path to the directory you want to delete files from.
The code starts by defining the $directory
variable which holds the path to the target directory.
Then, it calculates the threshold for deleting files older than 1 hour. The current timestamp is obtained using the time()
function and 3600 seconds (1 hour) are subtracted from it.
Next, the code opens the directory using the opendir()
function and starts looping through each file using the readdir()
function.
Inside the loop, it checks if the current item is a file (not a directory) and if its modification time (obtained with filemtime()
function) is older than the threshold. If both conditions are met, the file is deleted using the unlink()
function.
After looping through all the files, the directory handle is closed using the closedir()
function.