douben7493 2013-07-24 19:05
浏览 11
已采纳

如何使用php只保留特定文件并删除目录中的其他文件?

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);  
  • 写回答

4条回答 默认 最新

  • douzhi7661 2013-07-24 19:09
    关注
     $dir = "your_folder_path";  
     if ($opendir = opendir($dir)){
        //read directory
         while(($file = readdir($opendir))!= FALSE ){
          if($file!="." && $file!= ".." && $file!= "2.jpg"){
           unlink($file);
          }
         }
       } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部