The Hidden Cost of filemtime() and Directory Iteration
You are encountering the stat failed warning because your script is attempting to retrieve metadata for filenames that do not actually exist on the filesystem at the moment of execution. The specific error message, Warning: filemtime() [function.filemtime]: stat failed for post_1003463425.xml, indicates that the filemtime() function cannot locate the target file.
In your provided code snippet, you are iterating through a directory using opendir() and readdir(). The logic seems sound on the surface: check if the filename matches an .xml or .xsl pattern, retrieve its modification time, calculate the age, and delete it if it's older than 24 hours. However, there is a critical flaw in how you are handling the file list relative to the deletion operation itself.
The primary issue lies in the order of operations within your while loop. You open the directory handle, then enter a loop to read entries. Inside that loop, you check the filename against a regex pattern. If it matches, you immediately call filemtime($file). It is highly probable that $file contains a path or name that does not resolve correctly in your specific environment, or more likely, the file has already been deleted by a previous iteration of this same loop.
When you call unlink($file) inside the loop, you remove the file from the filesystem immediately. However, PHP's readdir() function maintains an internal list of entries read from the directory. It does not automatically refresh its view after a file is removed. If your regex matches a file, deletes it, and then proceeds to the next entry in the internal array, subsequent calls to filemtime() might fail if the logic inadvertently references a deleted resource or if the filename provided to the function contains characters that are invalid for the current user context (though less likely given the simple naming convention).
A more robust approach ensures you only attempt to operate on files that still exist when you try to access them. Furthermore, relying solely on opendir() and readdir() without checking the actual existence of the file before calling filemtime() can lead to silent failures or warnings if the filename contains invalid characters for the specific filesystem mount.
Here is a refined implementation strategy that mitigates these risks:
function deleteOldFiles() {
// Ensure the directory exists and is readable before attempting to open it
$directory = './xml';
if (!is_dir($directory)) {
return;
}
$handle = opendir($directory);
if (!$handle) {
return;
}
while (false !== ($file = readdir($handle))) {
// Skip the . and .. entries which are standard directory references
if ($file === '.' || $file === '..') {
continue;
}
// Check if the filename matches the required extension pattern
if (preg_match("/\.xml$|\.xsl$/i", $file)) {
// Construct the full path to ensure filemtime works correctly regardless of CWD
$fullPath = $directory . DIRECTORY_SEPARATOR . $file;
// Always verify the file exists before trying to get its stats.
// This prevents "stat failed" warnings if a file was deleted externally
// or removed by a previous iteration in a concurrent scenario.
if (!is_file($fullPath)) {
continue;
}
$fileLastModified = filemtime($fullPath);
// Calculate the age of the file in seconds
if (abs(time() - $fileLastModified) > 24 * 3600) {
unlink($fullPath);
}
}
}
closedir($handle);
}
By explicitly constructing the full path and verifying file existence with is_file() before calling filemtime(), you eliminate the possibility of passing a non-existent or invalid path to the function. This is particularly important if your application runs from a different working directory than where the files are stored, or if the ./ prefix in your original code was resolving unexpectedly.
Another consideration involves the use of regular expressions for filename matching. While convenient, using glob() with specific patterns (e.g., glob($directory . '/*.xml')) can often be more performant and less prone to edge-case errors than iterating via readdir() and applying regex filters. However, if you prefer the explicit control offered by opendir(), the existence check remains the most critical safety mechanism.
If you are working within a Laravel application context, handling file system operations usually involves leveraging the filesystem helper or the Storage facade to manage permissions and paths more securely, ensuring that relative paths like ./xml are resolved correctly relative to the storage root rather than the web root. For production environments, consider adding error logging around the unlink() operation to catch any permission denied errors that might occur after a file has been successfully validated but failed during deletion due to race conditions or ACL restrictions.
