Forum Moderators: coopster

Message Too Old, No Replies

recursive delete

recusive delete a directory

         

PHPcoder

10:42 pm on Nov 9, 2009 (gmt 0)

10+ Year Member



This doesnt work. as i expected

you could loop it like this too


<?
$mydir = "/path/to/dir/";
$d = dir($mydir);
while($entry = $d->read()) {
if ($entry!= "." && $entry!= "..") {
unlink($entry); //this failed
}
}
$d->close();
rmdir($mydir);
?>

[webmasterworld.com ]

So here is what i did.


<?php

$mydir = realpath("../path/relative/to/calling/file"); // real path for a relative directory
$d = dir($mydir);
while($entry = $d->read()) {
if ($entry!= "." && $entry!= "..") {
unlink($mydir."/".$entry); // this worked
}
}
$d->close();
rmdir($mydir);
?>


What actually happened in the first code example was that the file i placed. index.php was inside a subfolder public_html/gallery/index.php

The file in there was left intact and the file public_html/index.php was actually the file that was deleted or unlink(index.php)

With my changes you can now use this snippet in any site no matter the location within the website, all you need to do is find a way of populating realpath() either by hardcoding as i have or by variable with the relative directory to be deleted.

CAUTION! THIS COULD DELETE YOUR SITE IF USED INCORRECTLY
Please be aware that this will erase all files within the directory and will then delete the directory. If you are going to use this then test it in a safe location. preferably somewhere like public_html/test/test/test/ and only working 1 directory away to avoid loss of important files

dreamcatcher

7:02 pm on Dec 30, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the code and advice.

dc

PHPcoder

11:54 pm on Dec 31, 2009 (gmt 0)

10+ Year Member



thats no problem i would hate to see a site deleted because of incorrect use of the coding.