1

How to use php keep only specific file and remove others in directory?

example:
1/1.png, 1/2.jpeg, 1/5.png ...

the file number, and file type is random like x.png or x.jpeg, but I have a string 2.jpeg the file need to keep.

any suggestion how to do this??

Thanks for reply, now I coding like below but the unlink function seems not work delete anything.. do I need change some setting? I'm using Mamp

UPDATE

// explode string <img src="u_img_p/5/x.png">
$content_p_img_arr = explode('u_img_p/', $content_p_img);
$content_p_img_arr_1 = explode('"', $content_p_img_arr[1]);    // get 5/2.png">
$content_p_img_arr_2 = explode('/', $content_p_img_arr_1[0]);    // get 5/2.png
print $content_p_img_arr_2[1];    // get 2.png   < the file need to keep

$dir = "u_img_p/".$id;  
if ($opendir = opendir($dir)){
    print $dir;
    while(($file = readdir($opendir))!= FALSE )
        if($file!="." && $file!= ".." && $file!= $content_p_img_arr_2[1]){
            unlink($file);
            print "unlink";
            print $file;
        }
    }
} 

I change the code unlink path to folder, then it works!!

 unlink("u_img_p/".$id.'/'.$file);  
5
  • If and when you do find a solution, "I strongly suggest" you be very careful with this, and "make a backup" of your entire Web site/folders, before executing such a script. Commented Jul 25, 2013 at 3:13
  • why?? it only delete flie in dir... any reason why you suggest?? Commented Jul 25, 2013 at 3:15
  • 1
    I'm "just saying", be careful that's all. ;-) Commented Jul 25, 2013 at 3:17
  • haha Thanks I thought it will happen some error then remove all website folder Commented Jul 25, 2013 at 3:20
  • Good stuff, take care and you're quite welcome :) Commented Jul 25, 2013 at 3:22

4 Answers 4

2

http://php.net/manual/en/function.scandir.php

This will get all files in a directory into an array, then you can run a foreach() on the array and look for patterns / matches on each file.

unlink() can be used to delete the file.

$dir = "/pathto/files/"
$exclude[] = "2.jpeg";
foreach(scandir($dir) as $file) {
 if (!in_array($file, $exclude)) {
  unlink("$dir/$file");
 }
}

Simple and to the point. You can add multiple files to the $exclude array.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for reply. but the unlink() not work delete anything??
Don't forget to exclude . and .. or do an is_dir() check.
@OP: Check that the user php is running under has permissions to delete the files. Also, make sure the path is correct. You could add an echo $file; under foreach to help debug.
@Jack: Yes, I did this quickly, you could add . and .. to exclude[] or you could let it silently fail on those as unlink won't delete directories anyways.
The use of @ should be avoided whenever possible, if that's what you meant by silently fail :) it's better to know what you're trying to delete.
0
 $dir = "your_folder_path";  
 if ($opendir = opendir($dir)){
    //read directory
     while(($file = readdir($opendir))!= FALSE ){
      if($file!="." && $file!= ".." && $file!= "2.jpg"){
       unlink($file);
      }
     }
   } 

2 Comments

Thanks for reply. but why the unlink() not work delete anything??
check permissions of your folder and also path to folder
0
function remove_files( $folder_path , $aexcludefiles )
{
    if (is_dir($folder_path))
    {
        if ($dh = opendir($folder_path))
        {
            while (($file = readdir($dh)) !== false)
            {
                if( $file == '.' || $file == '..' )
                    continue ;

                if( in_array( $file , $aexcludefiles ) )
                    continue ;

                $file_path = $folder_path."/".$file ;
                if( is_link( $file_path ) )
                    continue ;

                unlink( $file_path ) ;
            }

            closedir($dh);
        }
    }
}


$aexcludefiles = array( "2.jpeg" )
remove_files( "1" , $aexcludefiles ) ;

Comments

0

I'm surprised people don't use glob() more. Here is another idea:

$dir = '/absolute/path/to/u_img_p/5/';
$exclude[] = $dir . 'u_img_p/5/2.jpg';

$filesToDelete = array_diff(glob($dir . '*.jpg'), $exclude);
array_map('unlink', $filesToDelete);

First, glob() returns an array of files based on the pattern provided to it. Next, array_diff() finds all the elements in the first array that aren't in the second. Finally, use array_map() with unlink() to delete all but the excluded file(s). Be sure to use absolute paths*.

You could even make it into a helper function. Here's a start:

<?php
    /**
     * @param  string $path
     * @param  string $pattern
     * @param  array $exclude
     * @return bool
     */
    function deleteFiles($path, $pattern, $exclude = [])
    {
        $basePath = '/absolute/path/to/your/webroot/or/images/or/whatever/';
        $path = $basePath . trim($path, '/');
        if (is_dir($path)) { 
            array_map(
                'unlink', 
                array_diff(glob($path . '/' . $pattern, $exclude)
            );

            return true;
        }

        return false;
    }
  • unlink() won't work unless the array of paths returned by glob() happen to be relative to where unlink() is called. Since glob() will return only what it matches, it's best to use the absolute path of the directory in which your files to delete/exclude are contained.See the docs and comments on how glob() matches and give it a play to see how it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.