PHP - Delete multi files

Asked

Viewed 34 times

0

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

Variables of Mysql:

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

Array where go poles:

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

Function where will eliminate 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 a mistake happened. Someone could 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)...

1 answer

2


Both the function file_exists as to function glob, must receive a string. How are you passing one array, the error is being shown.

An alternative is to use a 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 with the 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);
  • Very thankful! This is what I was failing! I’m already Good Reply.. Give me 1min

Browser other questions tagged

You are not signed in. Login or sign up in order to post.