Search code examples
phpdirectory-structure

Organizing user images


I am developing a social system where users can upload images.

I am not very sure how I should structure my files. The two ideas I have is the following:

  1. Add a folder with the userID as name and put all the users images in there
  2. Have a single folder for all images, and give each image a unique name

Which one of the two would be better? Is it the proper way to organize images?


Solution

  • It depends.

    When you use have a gallery with images stored in a directory per user, you also have to worry about duplicates (say user will upload several files with the same name).

    On the other hand in the first case you might run into performance issues related to number of files in a single directory (if you have more than 10k of files it might lag).

    Solution I like is is to create a unique name and crop it into several parts to create a directory structure.

    For example:

    1. Generate from a file image.jpg (look into the manual) a unique name, say nfsr53a5gb

    2. Add to it the original extension so it becomes nfsr53a5gb.jpg

    3. Split it with / into nf/sr/53/a5/gb.jpg

    4. Create missing folders as you go (see recursive parameter)

    You won't hit the penalty for number of files in a directory soon and you won't get a collision and files have URLs difficult to guess.

    A nice touch is to add a controller for getting those files which will change the name to the original name (store it in database and switch headers). Use it only for a dedicated download button as this might be too CPU and I/O intensive for many images embedded on a page.

    In order to do this you have to modify headers like this:

    Content-Disposition: attachment; filename=YOUR_FILE_NAME.YOUR_EXTENSION
    Content-Type: application/octet-stream