Filtering Directory Entries and Cleaning Subdirectories in PHP
When you run scandir() on a directory, it returns an array containing two dot-prefixed entries (. for the current directory and .. for the parent) followed by the actual files and subdirectories. The function itself does not distinguish between them; it simply lists every entry as a string. To identify which items are folders versus files, you must inspect the properties of each entry using the is_dir() function.
Consider your current setup where $target points to a directory used for zip uploads. After executing $scan = scandir($target);, you have a list of mixed content types. The standard pattern for iterating through these results involves checking the type before deciding on an action:
$scan = scandir($target);
foreach ($scan as $item) {
// Skip '.' and '..' entries
if ($item === '.' || $item === '..') {
continue;
}
// Check if the item is a directory
if (is_dir($target . '/' . $item)) {
echo "Found subdirectory: {$item}\n";
// Logic to delete the folder and its contents goes here
} else {
echo "Found file: {$item}\n";
// Logic to handle files goes here
}
}
The is_dir() function resolves the full path of the item and returns a boolean. This allows you to safely separate your logic into two distinct branches. If the item is a directory, you can proceed with cleanup tasks specific to folders. If it is a file, you might choose to keep it or move it elsewhere, depending on your application's requirements.
Handling Non-Empty Directories
You mentioned that rmdir() cannot delete folders containing content. This is expected behavior; rmdir() only removes empty directories. To remove a directory regardless of its contents, you need to use recursive() mode by calling rmdir() with the second argument set to true.
$fullPath = $target . '/' . $item;
if (is_dir($fullPath)) {
// Remove the directory and all files/subdirectories inside it
if (rmdir($fullPath, true)) {
echo "Successfully deleted directory: {$item}\n";
} else {
echo "Failed to delete directory: {$item}. Check permissions.\n";
}
}
While rmdir(..., true) handles the recursive deletion internally, it is important to understand what happens under the hood. It does not simply wipe the data; it iterates through the contents and deletes them one by one before removing the folder itself. This can be resource-intensive if the directory contains thousands of files or deeply nested structures.
Performance and Safety Considerations
Before running a recursive deletion script, consider the volume of data you are handling. If $target is intended for temporary zip extraction, ensuring it is empty after processing is crucial to prevent data leaks or permission issues in subsequent uploads. However, blindly deleting everything carries risks:
- Permission Errors: The user running the PHP process might lack write permissions on specific subdirectories, causing
rmdir()to fail silently or throw warnings depending on error reporting settings. - Symlinks: If any entry is a symbolic link pointing to a directory elsewhere on the filesystem,
rmdir()will attempt to follow the link. Depending on the OS and configuration, this might delete the target or fail. - Race Conditions: If files are being uploaded concurrently while you are scanning and deleting, you risk deleting active data. Ensure that no other process is writing to
$targetduring the cleanup window.
If your application framework allows it, Laravel provides helper methods like Storage::deleteDirectory() which abstracts these details, but when using native PHP functions as in your example, explicit error handling is mandatory. Always check the return value of rmdir(). A return value of false indicates failure, often due to permission issues or non-empty directories if the recursive flag was omitted.
Conclusion
By combining scandir() with is_dir() and utilizing the recursive option in rmdir(), you can effectively clean up a directory structure while preserving specific files. Always validate paths, handle errors explicitly, and ensure your script runs with appropriate privileges to avoid permission-related failures.