Solved

PHP Function to Find and Unlink Files Regardless of File Extension

Posted on 2010-09-04
8
458 Views
Last Modified: 2012-05-10
Hi, I'm stumped on this one- I have a start here, but I think I may need to just scratch it and start over.

What I need to do is create a function to search a directory for all files with a given filename, regardless of their extension, and then delete them.  For example, in the "docs" directory, find any files with the filename "Resume_1", and it might return "Resume_1.doc", "Resume_1.docx", "Resume_1.ppt", and so on.  All of these files should be deleted.

Anyway... here's what I have, but it's obviously incorrect.  :)

I'd be extremely grateful for any help!
function find($dir,$pattern){
 $files = array();
 if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
     if ($file != "." && $file != "..") {
        $posDec = strpos($file,".");
       $fileName = substr($file,0,$posDec);
       if($fileName == $pattern){
         array_push($files,$file);
        }
     }
   }
 }
 closedir($handle);
 return $files;
}


$dir = "../files/docs";
$fileName = "Resume_1";
$files = find($dir,$fileName);
$doc = $files['0'];
if (file_exists($doc)) unlink($doc);

Open in new window

0
Comment
Question by:sbcjr
8 Comments
 
LVL 1

Author Comment

by:sbcjr
Comment Utility
If this is too difficult, or if I've made it confusing, I can break it into multiple phases/steps....  :)
0
 
LVL 9

Expert Comment

by:MarkusId
Comment Utility
Hi,

I think the problem might be that there is no path in the $filename given back from readdir();

Please try the following:

After:
$doc = $files['0'];

also give:

echo $doc

and see, if it is only the filename or the filename including the directory path. If the directory path is not included you have to do:



if (file_exists($dir . "/" . $doc)) unlink($dir . "/" . $doc);

Open in new window

0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
Try this:
<?php
function find_files($dir,$pattern)
{   
   $files = array();   
   if (is_dir($dir))
   {      
      //echo "is dir";
      if ($dh = opendir($dir))
      {
         echo "Directory handle: $handle\n";
         while (($file = readdir($dh)) !== false)
         {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
            $tmp=explode(".",$file);
            print_r($tmp[0]."<br>");
            if ($tmp[0] == $pattern)
            {
               $files[] = $file;
            }
         }
         closedir($dh);         
      }
   }
   else
   {echo "not dir";}
   return $files;
}


$dir = "../files/docs/";
$fileName = "test1";
$f_files = find_files($dir,$fileName);
print_r($f_files);
foreach($f_files as $files)
{
   echo "deleting file:".$dir.$files;
   unlink($dir.$files);
}
php?>

Open in new window

0
 
LVL 4

Expert Comment

by:dmgroom
Comment Utility
I couldn't really see much of a problem with your code, but have tidied it up a little.

Note:

1) The file which are to be deleted will have to have the right permissions so that the user the web server is runnning as can delete them.

2) that I'd set $dir as a full system path not a relative directory path

function find($dir,$pattern){
 $files = array();
 if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
     if ($file != "." && $file != "..") {
        $posDec = strpos($file,".");
       $fileName = substr($file,0,$posDec);
       if($fileName == $pattern ){
		unlink($file);
        }
     }
   }
 }
 closedir($handle);
}

$dir = "./";
$fileName = "example";
find($dir,$fileName);

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 500 total points
Comment Utility
It is best done with a REGEX


function find($dir,$pattern){
     $files = array();
     if ($handle = opendir($dir)) {
          while (false !== ($file = readdir($handle))) {
         
               if ($file != "." && $file != "..") {

                    $regex = '~^('.$pattern.'\.[0-9a-zA-Z]+)$~';
                    if( preg_match( $regex, $file, $match ) > 0 ) {
                         array_push( $files, $file );
                    }

               }
          }
     }
     closedir($handle);
     return $files;
}


$dir = "../files/docs";
$fileName = "Resume_1";
$files = find($dir,$fileName);
$doc = $files['0'];

Open in new window

0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
You can use base name instead of explode
<?php
function find_files($dir,$pattern)
{
   $files = array();
   if (is_dir($dir))
   {
      echo "is dir";
      if ($dh = opendir($dir))
      {
         while (($file = readdir($dh)) !== false)
         {
            if (basename($file) == $pattern)
            {
               $files[] = $file;
            }
         }
         closedir($dh);
      }
   }
   else
   {echo "not dir";}
   return $files;
}

$dir = "/var/www/testarea/delete_files/";
$fileName = "test1";
$f_files = find_files($dir,$fileName);

foreach($f_files as $files)
{
   echo "deleting file".$dir.$files;
   unlink($dir.$files);
}
php?>

Open in new window

0
 
LVL 13

Expert Comment

by:darren-w-
Comment Utility
Sorry got that a little wrong, inside the first while loop in the function it should read:

            $info = pathinfo($file);
            if (basename($file,'.'.$info['extension']) == $pattern)
            {
               $files[] = $file;
            }
        

Open in new window

0
 
LVL 1

Author Closing Comment

by:sbcjr
Comment Utility
Absolutely superb!  Works perfectly!!

Thank you *all* very, very much for taking the time to respond and help me out.  I very sincerely appreciate it.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now