PHP 删除目录第一次不起作用


PHP delete directory doesn't work first time

我创建了一个链接到完成.php的按钮。它应该删除安装程序目录。问题是它在第一次尝试时失败,但在随后重新加载页面时会起作用:

function Delete($path){ 
    if (is_dir($path) === true){
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file){
            Delete(realpath($path) . '/' . $file);
        }
        return rmdir($path);
    }else if (is_file($path) === true){
        return unlink($path);
    }
    return false;
}
Delete('installer');
$filename = '../admin/installer/';
if (file_exists($filename)) { Delete('installer'); } else {header("Location: index.php");}

我认为您的删除功能不稳定。

您可以使用此功能删除文件夹,删除其所有文件和文件夹:

public static function deleteDir($dirPath) {
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            self::deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

来源 : https://stackoverflow.com/a/3349792/3444315