PHP: Remove Files by Extension Without Affecting Other Files
Need to Delete Specific File Types in PHP?
Sometimes, when working on a PHP project, you may need to remove only files with a certain extension (e.g., .jpg
) from a directory—without touching other file types. PHP makes this easy using just a few lines of code.
PHP Code to Remove Files with a Specific Extension
Create a file in your project directory (e.g., index.php
) and insert the following code:
<?php
$fullPath = __DIR__ . “/art/”;
array_map(‘unlink’, glob(“$fullPath*.jpg”));
?>
How It Works
- __DIR__: Returns the full directory path of the current file.
- glob(“$fullPath*.jpg”): Finds all .jpg files in the art/ folder.
- array_map(‘unlink’, …): Applies the unlink function to delete each matched file.
✅ Only .jpg files will be deleted — other file types like .png, .txt, or .php remain untouched.
Use Cases
- Cleaning up generated images
- Removing temporary files by extension
- Automated maintenance scripts
Safety Tip
Make sure the path and file extension are accurate before running this code to avoid accidentally deleting important files.
Final Thoughts
This small but powerful snippet helps automate file cleanup based on extension. It’s a handy trick for developers working with dynamic file generation or media uploads.
