Search code examples
phpmysqldatabaseimagestore

PHP Should I store image paths in a database?


I will have a website with a bunch of companies and each company will be able to upload their logo. Is it a good idea to just create a folder for each company who signs up, so it would be
companies/user1/logo.jpg and companies/user2/logo.jpg and just store everyone in a folder, that way I don't need the path to reference the image?

Or should I store them in one folder like company_logos/gaegha724252.jpg and they will all be random file names, and the path would be stored in the database associated with that company?

What are the advantages and disadvantages?

Thanks!


Solution

  • Using Folders for Organization

    Advantages: They are logically clear to someone fiddling with the system on the back end- that's about it really.

    Disadvantages: 'harder' to clean up when you delete a company, etc. and you have to make sure none of your directory names overlap, generally more work from the get go.

    Using Images in One Folder

    Advantages It's technically a bit easier to clean up and not all that much work.

    Disadvantages You'll have to write at minimum a very basic collision detection algorithm and a very basic 'random name generator'.

    Using the Database to Store Images

    Caution: Many lives have been lost in this argument!

    Advantages: Referential integrity, backing up/restoring is simpler, categorization

    Disadvantages: Fraught with pitfalls, potentially slower, more advanced storage/retrieval techniques, potential performance issues and increase of network requests. Also, most cheap hosting providers' databases are way too terrible for this to be a good idea.

    I highly recommend just using a hashed file name and storing it (the filename) in the database and then storing the images in a folder (or many folders) on disk. This should be much easier in the long run and perform better in general without getting too complicated.