Good day.

On the server is the img directory, in this directory the downloaded images for processing, the file extension that users upload there .jpg .Jpg .png .PNG .gif, etc.

When I run the code:

if (file_exists('./img')) foreach (glob('./img/*') as $file) unlink($file); echo("Файлы каталога успешно удалены, обновите страницу"); 

all files in the img directory are deleted.

Question: how to change this code so that the files specified by me are not deleted, for example:

  1. load.gif
  2. .htaccess

    2 answers 2

     if (file_exists('./img')) { foreach (glob('./img/*') as $file) { if ($file!='.htaccess') unlink($file); } echo("Файлы каталога успешно удалены, обновите страницу"); } 

    Like that

    • It works, thanks. - Viher
    • In case you need to save several files: $ keep = explode (',', 'load.gif, .htaccess, nestirat.jpg'); // necessary names separated by commas ... // and in a cycle if (! in_array ($ file, $ keep)) unlink ($ file); - Sergiks
     if (file_exists('./img/mini_logo')) { include('db.php'); $query = 'SELECT img FROM zayav'; $res = mysql_query( $query ); $img = array(); while ( $item = mysql_fetch_array($res)) { $img3 = $item['img']; $way="./img/mini_logo/$img3.png"; $img[] = $way; } foreach (glob('./img/mini_logo/*') as $file) { if( !in_array( $file, $img)) unlink($file); } echo "<script>history.go(-1);alert( 'Все ненужные файлы очищены!');</script>"; } 

    Here is my code. In the database file names without extensions, they refer to the real images in the folder. They set the task of clearing the folder of garbage (old images) but that the files used were not affected. Suddenly, someone will be useful.