Question

Say I want my uploaded files to be stored in a structure of subdirectories as shown below:

    /uploads/0/0/kitten.jpg;
    /uploads/0/1/kitten1.jpg;
    /uploads/1/10/pic.jpg;

So that each subfolder can contain 999 files at max i.e. when /uploads/0/ reaches its limit, the folder /uploads/1/ is created automaticaly and next file goes there. Each folder also can contain 999 subfolders.

The question is - How do I do that? My main concern is how to determine where to put the newly uploaded file. Could you describe the algorithm? I cannot think of anything better than performing these steps each time:

  1. Looking for the latest created folder in /uploads/ and if it's empty - creating one, like so:

    $contents = $scandir('/uploads');
        $dirs = array();
        foreach ($contents as $path) {
            if (is_dir($path)) {
              $dirs[] = $path;
            }
        }
        if (empty($dirs)) {
             //create new dir and save file there subsequently
             $saveTo = $parentDir . DIRECTORY_SEPARATOR . "1" . DIRECTORY_SEPARATOR . "1";
             mkdir($saveTo, 0777, true);
        } else {
            $last = array_pop($dirs);
        }
    
  2. We do basically the same for this subfolder and so on(and I guess I may want to use recursion here somehow). Am I moving in right direction here or maybe I am overcomplicating things? Is there a better way to do this? Anything, please. I am only beginner in php and coding.
Was it helpful?

Solution

One approach is to keep a running total of all uploads, (atomically) increasing it for each upload.

Then the directory can be created like so:

$dir = sprintf('/uploads/%d/%d', floor($total / 1000), $total % 1000);
if (!file_exists($dir)) {
    mkdir($dir, 0755, true);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top