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 deletion

  • Skip . and .. entries when using scandir()

  • Use unlink() to delete individual files

  • Consider 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.

Updated on: 2026-03-15T10:26:06+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements