Solved

PHP Function to Find and Unlink Files Regardless of File Extension

Posted on 2010-09-04
8
468 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
ID: 33602437
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
ID: 33602558
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-
ID: 33602563
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 4

Expert Comment

by:dmgroom
ID: 33602569
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
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 500 total points
ID: 33602590
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-
ID: 33602644
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-
ID: 33602657
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
ID: 33602664
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

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

830 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