0

I want delete all images from 'Logo' folder except an original image.

eg.

demo.jpg - original image

demo_50.jpg, demo_100.jpg, demo_150.jpg - other images.

Now i want to delete all images except demo.jpg using php

White Marcus
  • 195
  • 2
  • 3
  • 12

2 Answers2

2

You can maintain a list of file which you do not want to delete in a directory.

$dir = 'direcotry';
$keepFiles = array('demo.jpg');

foreach( glob("$dir/*") as $file ) {
    if( !in_array(basename($file), $keepFiles) )
        unlink($file);
}

Another solution to this is,

1.Move that original file from current directory say X to some other directory say Y

2.Remove the complete directory X

3.Now move back that original file from Y to X

Bhavya Shaktawat
  • 2,504
  • 1
  • 13
  • 11
  • can you help for my another issue.? – White Marcus Dec 12 '14 at 07:23
  • Error occurs during image uploading with german named image like (Logo_FC_Bayern_München). How to solve it. – White Marcus Dec 12 '14 at 08:16
  • move_uploaded_file($_FILES['document']["tmp_name"][$i],$clientFileUploadPath.$_FILES['document']["name"][$i]); – White Marcus Dec 12 '14 at 08:31
  • $_FILES['document']['tmp_name'] contains the uploaded file path. if you are uploading multiple file with array structure then only you need to use $_FILES['document']['tmp_name'][$i] Another thing make sure the directory in which you are moving files have proper permissions – Bhavya Shaktawat Dec 12 '14 at 10:22
  • i solved that issue using utf8_decode(). But this only works on local machine not in the live. can u help me? i also reached the maximum question limit in this site. please try to help mate. – White Marcus Dec 12 '14 at 10:25
  • can you please check the file permission in which you are moving uploaded files and also add your form code – Bhavya Shaktawat Dec 12 '14 at 11:10
  • i also gave 0777 permission. And files uploading is works fine. but a file name containing the special characters is not uploaded. – White Marcus Dec 12 '14 at 11:20
  • You can check this thread http://stackoverflow.com/questions/9838994/replace-special-characters-before-the-file-is-uploaded-using-php http://stackoverflow.com/questions/19444031/browser-could-not-read-filename-which-contains-special-characters – Bhavya Shaktawat Dec 12 '14 at 11:33
  • thanks for your suggestion mate. Very thank you for giving great time with me. – White Marcus Dec 12 '14 at 12:12
0

use unlink:

 if( !in_array($file, $original) )//$file is total file in the directory
        unlink($file);

see this post also:delete image from folder PHP

Community
  • 1
  • 1
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44