I want to to destroy all images within a folder with PHP how can I do this?
Asked
Active
Viewed 2.7k times
9
-
4No, please, don't destroy them. – Dejan Marjanović Apr 04 '11 at 06:25
-
4which of the 3674 other questions about http://stackoverflow.com/search?q=delete+images+in+a+folder+[php] have you checked and why didnt they answer your question? – Gordon Apr 04 '11 at 07:44
4 Answers
29
foreach(glob('/www/images/*.*') as $file)
if(is_file($file))
@unlink($file);
glob()
returns a list of file matching a wildcard pattern.
unlink()
deletes the given file name (and returns if it was successful or not).
The @
before PHP function names forces PHP to suppress function errors.
The wildcard depends on what you want to delete. *.*
is for all files, while *.jpg
is for jpg files. Note that glob
also returns directories, so If you have a directory named images.jpg
, it will return it as well, thus causing unlink
to fail since it deletes files only.
is_file()
ensures you only attempt to delete files.

Christian
- 27,509
- 17
- 111
- 155
6
The easiest (non-recursive) way is using glob()
:
$files = glob('folder/*.jpg');
foreach($files as $file) {
unlink($file);
}

ThiefMaster
- 310,957
- 84
- 592
- 636
4
$images = glob("images/*.jpg");
foreach($images as $image){
@unlink($image);
}

Dejan Marjanović
- 19,244
- 7
- 52
- 66
3
use unlink and glob function
for more see this link http://php.net/manual/en/function.unlink.php and http://php.net/manual/en/function.glob.php

Bhanu Prakash Pandey
- 3,805
- 1
- 24
- 16