PHP organizes uploaded photos

I am creating a PHP application that allows users to upload photos. To make it manageable, the folder must have a maximum of 5000 photos. Each uploaded photo will be assigned an identifier in the database, and the photo will be renamed to identifier.

How to check if a particular folder has 5,000 photos? Should I check the identifier of the last row in the photo table?

Folders should be named in stages. eg. folder_1, folder_2etc.

My suggested steps:

  • Get the last photo table insert ID
  • (Last_insert_ID + 1)% 5000 = Some_number (number of the folder in which it should be saved)
  • Save the photo in the_some_number folder. If the folder does not exist, create a new one.

Or is there a better way to do this?

+5
source share
6 answers
$last_id; // for example 9591
$current_folder = floor($last_id/5000);
$picture_num_in_folder = $last_id-($current_folder*5000);
if ($picture_num_in_folder == 5000)
    // new dir and such (new folderid = $current_folder+1 and $picture_num_in_folder = 1)
else
    // just place the picture with unique ID $last_id+1 called image_$picture_num_in_folder+1 in folder $current_folder
+2
source

I assume that reading the database will be faster than reading the file system.

You will be better off running a sql query and getting a count for each folder grouped.

// Example Query
SELECT COUNT(file), folderId As Count FROM photos WHERE folderId IN ('1', '2') GROUP BY folder
// It would be beneficial to have a flag on the folders that would enable or disable them
// that way you're not iterating through folders that we already know are > 5k
// You would run this and have seperate query that would pull in these folder names
// and passing them to the above query.
SELECT foldername, folderId FROM folders WHERE countFlag = 0;


//Example Conditional.
if($Count > 5000):
  // Over 5k Do Something
  //Since were over 5k, set this folders flag to 1
  // that way we arent iterating through it again
  $countFlag = 1;
else:
  // Under 5k Do Something else
endif;

Note: If you need real code samples, I can hack something quickly. The above examples do not contain actual working code and are intended for theoretical purposes only. You will need to iterate over the returned rows as they are grouped by folder.

+5
source

. , , . db. COUNT:

SELECT filepath, COUNT(filename) AS num FROM mytable
GROUP BY filepath;

, num < 5000.

+1

, , "" . , "folder_number" . , , 5000, , , ( ).

, , , .

+1

: , , , 1, c4ca4238a0b923820dcc509a6f75849b. /rootpath/images/c/4/c/ . mkdir() , mkdir( '/dir/c/4/c/', 0777, true );.

, - .

, WordPress ...

+1

, , 5000 , .

If the folder x should have a full 5000 files (because of the last ID greater than 5000 * x), this means that some images have been deleted. You cannot reassign this identifier in a row in your database so that you cannot replenish the space of deleted files.

-1
source

All Articles