Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

PHP Function to Find and Unlink Files Regardless of File Extension

Posted on 2010-09-04
8
Medium Priority
?
497 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 2000 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

604 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