Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Deleting All Files From A Folder Using PHP
In PHP, you can delete all files from a folder using builtin functions like glob() and scandir(). Both methods provide efficient ways to iterate through directory contents and remove files programmatically.
Using glob() Function
The glob() function searches for files matching a specified pattern and returns an array of file paths ?
Syntax
array|false glob(string $pattern, int $flags = 0)
Parameters
$pattern The search pattern (e.g., "folder/*" for all files)
$flags (optional) Modifies behavior with flags like GLOB_ONLYDIR, GLOB_NOSORT
Example
Here's how to delete all files from a folder using glob() ?
<?php
$folderPath = 'uploads';
$fileList = glob($folderPath . '/*');
foreach ($fileList as $file) {
if (is_file($file)) {
unlink($file);
echo "Deleted: " . basename($file) . "<br>";
}
}
echo "All files deleted from " . $folderPath;
?>
Using scandir() Function
The scandir() function returns an array of all items (files and directories) in a specified directory ?
Syntax
array scandir(string $directoryPath, int $sortingOrder = SCANDIR_SORT_ASCENDING)
Example
Here's how to delete all files using scandir() ?
<?php
function deleteAllFiles($folderPath) {
$files = scandir($folderPath);
foreach ($files as $file) {
if ($file !== '.' && $file !== '..') {
$filePath = $folderPath . '/' . $file;
if (is_file($filePath)) {
unlink($filePath);
echo "Deleted: " . $file . "<br>";
}
}
}
}
// Usage
deleteAllFiles('temp_files');
echo "Cleanup completed!";
?>
Comparison
| Method | Pattern Support | Performance | Best For |
|---|---|---|---|
glob() |
Yes (wildcards) | Faster | Selective deletion |
scandir() |
No | Slower | Complete directory listing |
Key Points
Always use
is_file()to verify items are files before deletionSkip
.and..entries when usingscandir()Use
unlink()to delete individual filesConsider error handling for permission issues
Conclusion
Both glob() and scandir() effectively delete all files from a folder. Use glob() for patternbased deletion and scandir() when you need complete directory control. Always test with noncritical files first.
