Problem Background
I have a multimedia web applications where users can save and delete files. The saved files are used for various application wide functionalities.
When files are saved, they are put deep inside directory tree (usually 6 to 9 folders deep). The files are put at such deep level to make sure that they are easily distinguishable by admin/superuser looking at file structure and to match with existing manual system.
For Example,
"UploadedAssets" is the root directory and can contain following folder structure :
\ith\sp\cookery\ckpe\interactives\timestep\blahblah\item1\image01.png
\ith\sp\cookery\ckpe\interactives\timestep\blah_only\item1\image02.png
\ith\sp\cookery\ckpe\interactives\timestep\blah_only\item2\image03.png
\ith\sp\cookery\abcd\interactives\timestep\blahblah\item1\image66.png
- The first 5 names are user selectable (from dynamic dropdown menus) form approx 20-25 options each.
- The last 3 depends on whatever user inputs (e.g. category , title, etc.). This is received from user using text input fields. These can be 1 or up to 4 directories.
- The last directory "item1" can have one or more files but no sub directories
- Each directory EXCEPT the last one (item1) can have other sub directories
- When I remove/delete a file, obviously program knows the full path of the file location.
Because of number of possible directory name options, even in the testing phase, the root "UploadedAssets" directory has exploded and there are plenty of empty unused directories and dead branches.
My question is
Once the user deletes one/more files from a directory (e.g. image01.png from item1),
- How can I traverse up the tree from deleted file (going only to straight parents) and delete the parent node if its empty.
- While deleting if one of the directoy has other children/files then not to delete that directory and finish the process.
- While deleting stop at pre-defined root directory OR
- Stop after going UP n directory levels
E.g. in the above given example directory structure,
if user deletes image01.png then it should delete item1 and blahblah directories
if user deletes image02.png then it should delete only its parent item1 directory
if user deletes image66.png then it should delete all parent directories including abcd
My Attempts / research
I know how to remove single directory using php's rmdir. But couldn't think on how can I use it recursively to solve my problem.
I have tried to get my head around following stuff, but I don't know if any of those can fit my problem PHP: Unlink All Files Within A Directory, and then Deleting That Directory