Delete folder and the files that contain it with PHP

0

I have a folder on the server with a path similar to: "/ var / tmp / files /", inside it I have sub-folders called with the user ID that uploads the files (eg 99, 101, 102 , 167 ...). Within these folders there may be 1 or more files in different formats of images and pdfs.

  • / var / tmp / files

    • 99
      • 99_img.jpg
      • 99_pdf.pdf
    • 101
      • 101_img.png
    • 102

    ... etc

I want to indicate an ID and delete all the subfolders + files inside, as long as they are smaller than that indicated ID (oldest). That is, if I indicate the number 102, the 102, 101, 99 should be deleted ... But not the 167.

On the other hand, I have a problem with the permissions, when trying to delete something, even if it is directly with unlink, it warns me:

PHP Warning:  unlink(/var/tmp/files/131/imagen.png): Permission denied 

What I have so far:

$dir_adjuntos = "/var/tmp/files/"
$path = $dir_adjuntos ."131";
$this->rrmdir($path);

public function rrmdir($dir) { 

    if (is_dir($dir)) { 
        $objects = scandir($dir); 
        foreach ($objects as $object) { 
            if ($object != "." && $object != "..") { 
            if (is_dir($dir."/".$object)) {
                $this->rrmdir($dir."/".$object);
            }
            else {
                unlink($dir."/".$object); 
            }
        }
    }
    $this->rrmdir($dir); 
    } 
}

How can I solve the deletion of folders with ID

asked by Norak 22.05.2018 в 17:12
source

1 answer

0

I think this could work for you.

$maxID = '120';
$dir_adjuntos = "/var/tmp/files/"
$path = $dir_adjuntos ."131";
$this->rrmdir($path);

public function rrmdir($dir) { 

    if (is_dir($dir) and ($dir < $maxID) {
        chmod($dir, '0777'); 
        $objects = scandir($dir); 
        foreach ($objects as $object) { 
            if ($object != "." && $object != "..") { 
            if (is_dir($dir."/".$object)) {
                $this->rrmdir($dir."/".$object);
            }
            else {
                chmod($object, '0777');
                unlink($dir."/".$object); 
            }
        }
    }
    $this->rrmdir($dir); 
    } 
}

With a variable that tells us what the maximum ID is, we compare it at the beginning of everything, when we evaluate whether we are in a folder or not. In case of being a folder, we also change the permissions and then can delete it.

Later, just before doing the unlink, we make a chmod to change the permissions in the folder and allow it to be deleted.

    
answered by 22.05.2018 в 17:22