Search code examples
phpimageuploadfile-organization

PHP organize uploaded photos


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

How do I check if a certain folder has 5000 photos? Should I check the ID of the last row in the photo table?

Folders shall be named incrementally. eg. folder_1, folder_2, etc.

My proposed steps:

  1. Retrieve last insert ID of photo table
  2. (Last_insert_ID + 1) % 5000 = Some_number (The folder number it should be saved in)
  3. Save photo to folder_some_number. If folder not exist, create new one.

Or is there a better way to do this?


Solution

  • $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