[英]How to delete all folders and files in a directory except a specific folder in PHP
[英]How to delete all files except one from a directory using PHP?
我有几个目录,其中有一些文件:
/test1/123.jpg
/test1/124.jpg
/test1/125.jpg
/test2/123.jpg
/test2/124.jpg
我想删除除/test1/124.jpg or /test2/124.jpg
之外的所有/test1/124.jpg or /test2/124.jpg
?
我知道目录名和文件名。 有没有办法在带有 php 的 Linux 环境中做到这一点,也许unlink
?
只需编辑 $dir 和 $leave_files 即可编辑位置和文件。
$dir = 'test1';
$leave_files = array('124.jpg', '123.png');
foreach( glob("$dir/*") as $file ) {
if( !in_array(basename($file), $leave_files) ){
unlink($file);
}
}
您将为每个目录运行一次。
如果目标目录与此脚本不在同一文件夹中,请记住将 $dir 设为完整路径(没有尾部斜杠)。
也许有点粗糙,但如果你在 Linux 系统上,你可以这样做(假设你在正确的目录中):
<?php shell_exec('rm $(ls * | grep -v '.$fileYouWantToKeep.')'); ?>
如果包含任何用户输入,您显然需要过滤该变量。
8 年前我写了这个被接受的快速黑客,但请考虑到
rm
和mv
删除和移动 shell 命令。shell_exec
上捕获错误也不是微不足道的,因为您没有像使用exec或system这样的替代方案那样获得退出代码)但是,它的优点是可以在单个 shell 命令中运行所有删除操作,并且不需要对每个处理过的文件进行额外的排除查找,这使得它在高删除率与保留率的情况下运行得非常快,如果您正在寻找性能:
for ($i=1;$i<=2;$i++){
shell_exec ('mv /test'.$i.'/124.jpg /test'.$i.'/keep.jpg');
shell_exec ('rm /test'.$i.'/12*.jpg');
shell_exec ('mv /test'.$i.'/keep.jpg /test'.$i.'/124.jpg');
}
无论如何,如果您在这里查看其他一些提出基于取消链接的解决方案的答案是在我的之后添加的,这(如下面的评论中所述)是一种更好的方法,我也建议这样做
添加错误处理,因为当文件正在使用或不允许脚本执行用户修改它时, unlink
可能会因权限问题无法删除现有文件。
总是ini_get('
max_execution_time ');
在运行脚本处理不知不觉长的文件列表之前检查您的脚本执行超时设置(并考虑在必要时使用set_time_limit为您的脚本扩展它)。
这是另一种选择:
<?php
$dirList = array('/path/to/dir1','/path/to/dir2'); //List of Dirs with files to be deleted. No trailing slash
$saved = array('path/to/file1','path/to/file2'); //List of files to be saved, no leading slash
foreach($dirList as $directory){
$list = scandir($directory);
foreach($list as $file){
if(!is_int(array_seach($directory.'/'.$file,$saved))){ //Array search returns key if needle exists, so we check if it does not return int
unlink($file);
}
}
}
?>
我现在无法访问我的服务器,所以我还没有测试它,但我认为它应该可以工作。 首先在一些测试目录上尝试一下,看看它是否有效。
您可以将文件移动到临时文件夹,然后删除该文件夹,创建一个新的粉丝并使用旧文件夹的名称移动文件夹,然后将照片移回,删除 tmp 文件夹。 $ 利润 $
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.