douben7493 2013-07-25 03: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-25 03: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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?