PHP - Fatal error: Cannot redeclare delete_directory() previously declared on line 4
I am running a loop to delete old members files but I get the following error below and I was wondering how can I correct it so that I can delete more then one members 开发者_如何学JAVAfiles?
Fatal error: Cannot redeclare delete_directory() previously declared on line 4
Here is PHP code.
for($x = 0; $x < count($delete_member); $x++){
//delete members files and folders from the server
$dirname = './members/' . $delete_member[$x] . '/';
function delete_directory($dirname) {
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
}
if (!$dir_handle) {
return false;
}
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)) {
unlink($dirname."/".$file);
} else {
delete_directory($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
delete_directory($dirname);
}
Take the definition of the delete_directory
function out of the loop. You only need to define it once to call it as many times as you need.
Judging by your comment, you are not familiar with basic PHP syntax, so I will show the correction below:
function delete_directory($dirname) {
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
}
if (!$dir_handle) {
return false;
}
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)) {
unlink($dirname."/".$file);
} else {
delete_directory($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
for($x = 0; $x < count($delete_member); $x++){
//delete members files and folders from the server
$dirname = './members/' . $delete_member[$x] . '/';
delete_directory($dirname);
}
I recommend buying an introductory PHP book and reading up a bit
精彩评论