Search code examples
phpfileunlink

PHP - Deleting folder/files only if there are no more in there


$value can = a folder structure to the language file. Example: languages/english.php

$value can also = the files name. Example: english.php

So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).

foreach($module['languages'] as $lang => $langFile)
{
        foreach ($langFile as $type => $value)
        {
            @unlink($module_path . '/' . $value);
            // Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
            // And ONLY if there are NO OTHER files within that folder also.
        }
}

How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.

And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.

Thanks guys :)

EDIT

Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:

foreach($module['languages'] as $lang => $langFile)
{
    foreach ($langFile as $type => $value)
    {
        if (@unlink($module_path . '/' . $value))
            @rmdir(dirname($module_path . '/' . $value));
    }
}

NEVERMIND, this works a CHARM!!! Cheers Everyone!!


Solution

  • Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.

    $file_path = $module_path . '/' . $value;
    
    if (@unlink($file_path)) {
        @rmdir(dirname($file_path));
    }