PHP - Delete multi files

0

I created a way to delete multiple files from a folder via MySQL .

MySQL Variables :

   $location_files = $listed['ads_image_1'];                    
   $location_files2 = $listed['ads_image_2'];                    
   $location_files3 = $listed['ads_image_3'];

Array where it goes:

   $remove_files = array($location_files, $location_files2, $location_files3);

Function where you will delete them:

   if(file_exists($remove_files)) {

                      $files = glob($remove_files); // get all file names
                         foreach($files as $file){ // iterate files
                           if(is_file($file))
                              unlink($file); // delete file
                      }   
               }   

But there was a mistake. Could someone help?

Error:

  Warning: file_exists() expects parameter 1 to be a valid path, array given in D:\xampp\htdocs\Superfacil_v1.7.9\myads.php on line 819 (if(file_exists)...
    
asked by anonymous 15.04.2018 / 19:03

1 answer

2

Both the file_exists function and the glob , function should receive a string . Since you are passing an array , the error is being displayed.

An alternative is to use foreach , for example:

<?php

$remove_files = array($location_files, $location_files2, $location_files3);

foreach($remove_files as $location) {

    if(file_exists($location)) {
        $files = glob($location); // get all file names

        foreach($files as $file){ // iterate files
            if(is_file($file))
                unlink($file); // delete file
        }   
    }   
}

Or you can use a callback function with array_map , for example:

<?php

function removeFiles($location) {
    if(file_exists($location)) {
        $files = glob($location); // get all file names

        foreach($files as $file){ // iterate files
            if(is_file($file))
                unlink($file); // delete file
        }   
    }  
}

$remove_files = array($location_files, $location_files2, $location_files3);

array_map('removeFiles', $remove_files);
    
15.04.2018 / 19:11