PHP to store images in MySQL or not?

前端 未结 16 2614
离开以前
离开以前 2020-11-28 05:56

I have built a small web application in PHP where users must first log in. Once they have logged in, I intend on showing a small thumbnail as part of their \"profile\".

相关标签:
16条回答
  • 2020-11-28 06:17

    I have implemented both solutions (file system and database-persisted images) in previous projects. In my opinion, you should store images in your database. Here's why:

    1. File system storage is more complicated when your app servers are clustered. You have to have shared storage. Even if your current environment is not clustered, this makes it more difficult to scale up when you need to.
    2. You should be using a CDN for your static content anyways, and set your app up as the origin. This means that your app will only be hit once for a given image, then it will be cached on the CDN. CloudFront is dirt cheap and simple to set up...there's no reason not to use it. Save your bandwidth for your dynamic content.
    3. It's much quicker (and thus cheaper) to develop database persisted images
    4. You get referential integrity with database persisted images. If you're storing images on the file system, you will inevitably have orphan files with no matching database records, or you'll have database records with broken file links. This WILL happen...it's just a matter of time. You'll have to write something to clean these up.

    Anyways, my two cents.

    0 讨论(0)
  • 2020-11-28 06:18

    In my case, i store files in file system. In my images folder i create new folder for each item named based on item id (row from db). And name images in an order starting from 0. So if i have a table named Items like this:

           Items      
    |-----|------|-----|
    | ID  | Name | Date|
    |-----|------|-----|
    | 29  | Test1| 2014|
    |-----|------|-----|
    | 30  | Test2| 2015|
    |-----|------|-----|
    | 31  | Test3| 2016|
    |-----|------|-----|
    

    my images directory looks like something like:

    images/
          29/
          30/
          31/
    
    
    images/29/0.png
    images/29/1.jpeg
    images/29/2.gif
    

    etc.

    0 讨论(0)
  • 2020-11-28 06:22

    As everybody else told you, never store images in a database. A filesystem is used to store files -> images are files -> store them in filesystem :-)

    0 讨论(0)
  • 2020-11-28 06:24

    I would suggest you do not store the image in your db. Instead since every user will be having a unique id associated with his/her profile in the db, use that id to store the image physically on the server.

    e.g. if a user has id 23, you can store an image in www.yourname.com/users/profile_images/23.jpg. Then to display, you can check if the image exists, and display it accordingly else display your generic icon.

    0 讨论(0)
提交回复
热议问题