?
Solved

PHP Function to Find and Unlink Files Regardless of File Extension

Posted on 2010-09-04
8
Medium Priority
?
488 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
WordPress Tutorial 1: Installation & Setup

WordPress is a very popular option for running your web site and can be used to get your content online quickly for the world to see. This guide will walk you through installing the WordPress server software and the initial setup process.

 
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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Introduction to Processes
Suggested Courses

752 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