How to delete all jpg files inside a folder with PHP

1

I have several folders with images that I need, by PHP, to delete all the .JPG files before starting a certain function, without deleting the subfolders that are inside.

How can I make this function delete the JPG without deleting the subfolders?

The folder looks like this:

imagem/01.JPG
imagem/02.JPG
imagem/original/01.JPG
imagem/original/02.JPG

I want to delete only the first 2 "image / 01.JPG and image / 02.JPG"

    
asked by anonymous 13.03.2018 / 16:08

2 answers

6

You can do this:

array_map('unlink', glob("caminho/completo/*.JPG"));

The glob will return an array with all possible paths (referring to .JPG files within the given folder).

array_map will apply the unlink function to each element of the array.

unlink will remove the file corresponding to the path.

Font

    
13.03.2018 / 16:36
3

You can use glob as @JuniorNunes suggested , but glob is case-sensitive (it is case-sensitive), that is, if it has files like this:

  • 1.JPG
  • 2.Jpg
  • 3.jpg

Only 1.JPG will be deleted, ie 2.Jpg and 3.jpg will be kept, which I believe is not what you want.

The ideal would be to do this:

array_map('unlink', glob('images/*.[Jj][Pp][Gg]'));

With [Jj][Pp][Gg] it will recognize the extension independently if it has any upper or lower case.

    
13.03.2018 / 16:46