admin管理员组

文章数量:1122832

Need help with WordPress to remove custom physical folders.

I am developing a WordPress plugin to use custom physical folders in the Media Library. The functionalty of the 1st version is quite basic: 1) create folder, 2) rename a folder, 3) delete a folder. Everything works fine (including uploading to, deleting from, etc.). But after installing some other plugins the folders on the server aren't getting deleted. The basic deletion process: a button in the interface triggers an ajax script that triggers a wp_ajax_function. In my case I allow deleting only empty folders. (Made intentionally to prevent the user deleting all the media by mistake.)

The php function for deleting a folder (its most important part):

function delete_directory($dir) {

// Check if the folder exists
if (!file_exists($dir) || !is_dir($dir)) {
    $response['fail'] = 'Folder not found.';
    return $response;
}

// Check if the folder has at least one subfolder
$subfolders = glob($dir . '/*', GLOB_ONLYDIR);
if (!empty($subfolders)) {
    $response['fail'] = 'The folder has one or more subfolders.';
    return $response;
}

// Check if the folder contains files other than index.php
$files = scandir( $dir );
$files_to_delete = array_filter( $files, function ($file) {
    return $file !== '.' && $file !== '..' && $file !== 'index.php';
} );


if ( !empty( $files_to_delete ) ) {
    $response['fail'] = 'The folder has one or more files.';
    return $response;
}

// Check if index.php exists
$indexFilePath = $dir . '/index.php';
if (file_exists($indexFilePath)) {
    unlink($indexFilePath); // Remove index.php
}

// Remove the directory
if (!rmdir($dir)) {
    $response['fail'] = 'Failed to delete the folder.';
} else {
    $response['ok'] = 'Folder deleted successfully.';

}

return $response;

} ` (The index.php file (<?php // Silence is golden.) is created on the fly during the creation of all new folders to prevent direct access from the browser to the files in it.)

Have tried different approaches: recursive rmdir, change chmod, etc.

The folders just don't get deleted after installing some plugins. Maximum success was using recursive rmdir: the folders were removed for a while, but then got recreated again. My guess the plugins somehow take permissions, or some other processes prevent deleting the folders. Any advice is appreciated.

(Without those plugins everyting worked fine.)

本文标签: ajaxRemoving custom physical folders with rmdir