1

I am trying to delete a folder with files inside of it but the following code does delete the files, but not the folder.

$nameFolder = $_GET['delete'];
$dir = '../projecten/projecten/'.$nameFolder.'';
$filesIN = glob($dir."/"."*");
$status = 'false';

foreach($filesIN as $files) //here i take all the files
    unlink($files);

$status = 'true';
if($status=='true'){
    rmdir($dir);
    $status = 'false';
}
doppelgreener
  • 5,471
  • 9
  • 47
  • 62
Ajeo
  • 73
  • 3
  • 11

3 Answers3

3

[edited] Only empty directories can be deleted.

Try:

<?php
//recursively remove a directory
function rrmdir($dir) {
    foreach(glob($dir . '/' . '*') as $file) {
        if(is_dir($file)){
            rrmdir($file);
        }else{
            unlink($file);
        }
    }
    rmdir($dir);
}

//Example
$nameFolder = $_GET['delete'];
$dir = '../projecten/projecten/'.$nameFolder.'';
rrmdir($dir);
?>

source: http://www.php.net/manual/pt_BR/function.rmdir.php#108113

Guilherme Nascimento
  • 8,794
  • 8
  • 51
  • 118
1

I would check the file permissions. On linux:

ls -al /path/to/projecten/projecten/

In simple terms the web server user must have write access to the directory in order to delete the file, for example the user www-data. In the below example the user lt can delete the test file:

drwxrwxr-x 2 lt lt 4096 Apr 29 08:54 test

Also I don't understand this bit of code:

$status = 'true';
if($status=='true'){
   rmdir($dir);
   $status = 'false';
}

Why not just have:

rmdir($dir);

As $status will always be 'true'.

You could also try using a system call, eg:

system `rm -rf /full/path/to/projecten/projecten/$nameFolder`;

Be very careful with that system command though - If you delete the wrong directory there is no going back!

A safer system command to use if you know the directory is empty would be:

system `rmdir /full/path/to/projecten/projecten/$nameFolder`;

But as pointed out in the comments above be very careful deleting a directory based on a $_GET variable. Imagine if the GET variables was '../../projecten' especially with the 'rm -rf' system command

someuser
  • 2,211
  • 4
  • 26
  • 39
0

Not an answer, but please change:

$nameFolder = $_GET['delete'];

To:

$nameFolder = basename($_GET['delete']);

And you may want to also add a:

 if (is_dir('../projecten/projecten/'.$nameFolder) {
     // ... do stuff here
 } else {
     // not a valid path
 }
Tigger
  • 8,757
  • 4
  • 36
  • 39