Solved

PHP Function to Find and Unlink Files Regardless of File Extension

Posted on 2010-09-04
8
462 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

A short article about problems I had with the new location API and permissions in Marshmallow
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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 …

911 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

16 Experts available now in Live!

Get 1:1 Help Now