Search code examples
phpcodeigniterunlink

How to delete a file which have such type of extensions in php?


What I'm trying to do is, to delete files which includes only such type of extensions.

Let's say a folder Images/ contains following files,

a.jpg
b.jpeg
c.php
d.php2
c.png

So now I want to delete only those c.php,d.php2. Is there any way to do this in a single step or any ideas ?

Note: In this case, I do not know exact name of the file or extension.

Thank you in advance.


Solution

  • To delete specific extension files from sub directories, you can use the following function. Example:

    <?php 
    function delete_recursively_($path,$match){
       static $deleted = 0,
       $dsize = 0;
       $dirs = glob($path."*");
       $files = glob($path.$match);
       foreach($files as $file){
          if(is_file($file)){
             $deleted_size += filesize($file);
             unlink($file);
             $deleted++;
          }
       }
       foreach($dirs as $dir){
          if(is_dir($dir)){
             $dir = basename($dir) . "/";
             delete_recursively_($path.$dir,$match);
          }
       }
       return "$deleted files deleted with a total size of $deleted_size bytes";
    }
    ?>
    

    e.g. To remove all text files you can use it as follows:

    <?php echo delete_recursively_('/home/username/directory/', '.txt'); ?>