Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store image files in the backend of a site

I'm building a site, and have just started getting into developing the backend.

The point of my site will be to display images to a visitor. For development purposes, I'd like to test everything first before going live.

I'd like to know what the best way of storing these images is. I've just finished setting up my Wamp server, and added a new db with phpMyAdmin. I found that I can store each image directly in the mySQL database as a BLOB data type. But is this the best way to go?

Thank you!

like image 423
user3871 Avatar asked Feb 13 '12 20:02

user3871


People also ask

How do you store images in backend?

A better approach would be to store the images as files in the filesystem and just store the filename in your database. that way, you can offload the entire image serving to the web server and never involve PHP in the HTTP requests for the file.

Should I store images in backend or frontend?

Typically, you'll store images for your website in a directory called "imgs" underneath your root htdocs or public directory. This is considered the front end; you don't really store images in a backend or DB unless you're storing links to those images and providing those links via an API call.

How do servers store images?

Most usually, you will store the files in the server filesystem (or some accessible network folder) and your database should store the relative or full path to them. That way, if an user requests the file with id 250, you will retrieve the entry from the database "Document" (or whatever) table, and get its full path.


2 Answers

This is most certainly not the way to go. You will then need to keep the blob in memory in PHP before sending it to the browser.

A better approach would be to store the images as files in the filesystem and just store the filename in your database. that way, you can offload the entire image serving to the web server and never involve PHP in the HTTP requests for the file.

like image 170
Emil Vikström Avatar answered Sep 20 '22 01:09

Emil Vikström


Storing files into database has two main advantages:

  1. Transaction safety. If the user edits his profile (pic & birth date), then either both get saved or neither in case of a rollback / error.

  2. Just one backup point. It will not happen to you to forget to backup the directory containing user avatars.

However, because of many pitfalls, I don't recommend it, especially not using PHP & MySQL. MySQL doesn't support streaming, so in case of a big file, you're going to use up all your ram.

The filesystem is undoubtfully the fastest and most natural way way. It has the least overhead and is the least resource-hungry.

Read:

Storing a file in a database as opposed to the file system?

Storing Documents as Blobs in a Database - Any disadvantages?

like image 44
Rok Kralj Avatar answered Sep 21 '22 01:09

Rok Kralj