Hello, I've been trying to find an elegant way to delete all files in a directory that aren't .jpg files. I also need to exclude a single file (let's call it keep.php) from deletion. I've been looking into the glob function, however the best I can come up with is how to delete ONLY .jpg files. I'm sure it's an easy fix... any ides? Thanks, Peter
glob should work for this or opendir can you just loop through the files and specify which ones to delete or omit from deletion?
Hi Here is the Solution <?php $dir = "./"; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { $array_name=explode(".",$file); $extension=$array_name[1]; if(strtolower(trim($extension))=="jpg") { unlink($dir.$file); print "Deleted > ".$file."<br>"; } } closedir($dh); } } ?> PHP: Thanks,
They want to delete all files that AREN'T a jpg file so you'd have to modify your if statement to be !="jpg" rather than =="jpg"
So I guess glob() isn't the solution here? Is it possible to accomplish this using glob()? Thanks for the help. -Peter
Hi, It can also be done by glob function here is the code <?php foreach (glob("*.*") as $filename) { $array_name=explode(".",$filename); $extension=$array_name[1]; if(strtolower(trim($extension))!="jpg") { unlink($filename); print "Deleted > ".$filename."<br>"; } } ?> PHP: Thanks,
One thing about your code.. doing "$extension=$array_name[1];" isn't a good idea because what if the filename has periods in it? $extension= substr($filename, strrpos($filename, ".")+1); PHP:
This should skip all capitalization and extra periods in file: <?php $file_list = glob("*.*"); foreach($file_list as $file_name){ $extension = strtolower(end(explode('.',$file_name))); if($extension != 'jpg' && $extension != 'jpeg'){ unlink($file_name); } } PHP: Peace,
That should work, azizny, except I think you meant to use the && operator, not the || operator. With that method, it'll delete every file including jpgs and jpegs.
Great. One of the problems I was running into was files with periods in the names, and I appreciate the help. Thanks a lot guys, rep added. -Peter