I have a few directories with some files in them:
/test1/123.jpg
/test1/124.jpg
/test1/125.jpg
/test2/123.jpg
/test2/124.jpg
I want to delete all except for /test1/124.jpg or /test2/124.jpg
?
I know the directory name and the file name. Is there a way of doing that in a Linux environment with php and maybe unlink
?
8 years ago I wrote this quick hack that got accepted but please take on account that
rm
and mv
delete and move shell commands.shell_exec
is not trivial since you do not get the exit code as you can do with alternatives like exec or system)However it has the advantage of running all deletions in a single shell command and it does not require an extra exclusion lookup per processed file, which makes it run quite fast on high deletion vs. preserving ratios, if performance is what you are looking for:
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');
}
Anyway if you look right here a few other answers that propose an unlink based solution were added after mine, which (as discussed in the comments below) is a much better approach, to which I'd also suggest
Adding error handling, as unlink
might fail to delete an existing file on permission issues when the file is in use or the script execution user is not allowed to modify it.
Always ini_get('
max_execution_time');
to check your script execution timeout settings (and consider using set_time_limit to extend it for your script if necessary) before running a script processing an unknowingly long list of files.