PHP to store images in MySQL or not?

前端 未结 16 2630
离开以前
离开以前 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:07

    Challenging the Conventional Wisdom!

    Of course it is context dependent, but I have a very large application with thousands of images and documents stored as BLOBS in a MySQL database (average size=2MB) and the application runs fine on a server with 256MB of memory. The secret is correct database structure. Always keep two separate tables, one of which stores the basic information about the file, and the other table should just contain the blob plus a primary key for accessing it. All basic queries will be run against the details table, and the other table is only access when the file is actually needed, and it is accessed using an indexed key so performance is extremely good.

    The advantages of storing files in the database are multiple:

    1. Much easier backup systems are required, as you do not need to back up the file system
    2. Controlling file security is much easier as you can validate before releasing the binary (yes, you can store the file in a non-public directory and have a script read and regurgitate the file, but performance will not be noticeably faster.
    3. (Similar to #1) It cleanly separates "user content" and "system content", making migrations and cloning easier.
    4. Easier to manage files, track/store version changes, etc, as you need fewer script modifications to add version controls in.

    If performance is a big issue and security and backups aren't (or if you have a good fs backup system) then you can store it the the FS, but even then I often store files (in the case of images) in the DB and building a caching script that writes the image to a cache folder after the first time it's used (yes, this uses more HD space, but that is almost never a limiting factor).

    Anyway, obviously FS works well in many instances, but I personally find DB management much easier and more flexible, and if written well the performance penalties are extremely small.

提交回复
热议问题