---
title: "PHP: Remove Files by Extension Without Affecting Other Files"
url: https://jeenus.in/php-remove-files-by-extension-without-affecting-other-files/
type: post
date: 2025-04-07
modified: 2026-09-14
markdown_url: https://jeenus.in/php-remove-files-by-extension-without-affecting-other-files.md
author: "Jeenus A"
---

# 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.

 
 ![renaming file extension](https://jeenus.in/wp-content/uploads/2025/04/ChatGPT-Image-Apr-7-2025-06_53_27-PM.png)
