Help deleting files

Hi all, I am trying to delete a directory called “news” and any text files inside.

My code works when the directory exists, but errors if the folder is not there, and I need it to do nothing if the directory doesnt exist.
I know I need to use file_exists, but cant seem to get the syntax right and I am unsure as to where exactly to put it in my code. I lifted the code from an example and got it to work.
Can anybody help
much appreciated

Here is the code:

[php]<?php
function deleteDir($dir) {
// open the directory
$dhandle = opendir($dir);

if ($dhandle) {
// loop through it
while (false !== ($fname = readdir($dhandle))) {
// if the element is a directory, and
// does not start with a ‘.’ or ‘…’
// we call deleteDir function recursively
// passing this element as a parameter
if (is_dir( “{$dir}/{$fname}” )) {
if (($fname != ‘.’) && ($fname != ‘…’)) {
echo “Deleting Files in the Directory: {$dir}/{$fname}
“;
deleteDir(”$dir/$fname”);
}
// the element is a file, so we delete it
} else {
echo “Deleting File: {$dir}/{$fname}
“;
unlink(”{$dir}/{$fname}”);
}
}
closedir($dhandle);
}
// now directory is empty, so we can use
// the rmdir() function to delete it
echo "Deleting Directory: {$dir}
";
rmdir($dir);
}

// call deleteDir function and pass to it
// as a parameter a directory name
deleteDir(“news”);
?>
[/php]

Try to put “rmdir” inside if.
$dhandle are false because directory doesn’t exists or you don’t have privileges to show this directory.

This code must works :
[php]

<?php function deleteDir($dir) { // open the directory $dhandle = opendir($dir); if ($dhandle) { // loop through it while (false !== ($fname = readdir($dhandle))) { // if the element is a directory, and // does not start with a '.' or '..' // we call deleteDir function recursively // passing this element as a parameter if (is_dir( "{$dir}/{$fname}" )) { if (($fname != '.') && ($fname != '..')) { echo "Deleting Files in the Directory: {$dir}/{$fname}
"; deleteDir("$dir/$fname"); } // the element is a file, so we delete it } else { echo "Deleting File: {$dir}/{$fname}
"; unlink("{$dir}/{$fname}"); } } closedir($dhandle); rmdir($dir); } // now directory is empty, so we can use // the rmdir() function to delete it echo "Deleting Directory: {$dir}
"; } // call deleteDir function and pass to it // as a parameter a directory name deleteDir("news"); ?>

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service