4

We just set up an open-source PHP/MySQL based software solution internally and almost all of it works the way we want it to, but file uploads are not what we would like. Currently, the only way it handles "uploads" is by storing/displaying a remote URL but we need to keep things internal.

Is there a best practice concerning how to store uploaded user files? Should they be stored on the file system or in the database? What are the pros/cons of each approach? Is one easier to implement given it already uses PHP and MySQL? Is there a hybrid approach that is better?

tpg2114
  • 14,112
  • 6
  • 42
  • 57
  • 2
    Ideally you would store the files in the filesystem normally and create database entries to store uploader information, a real file path and timestamps. This way you can index all the files, search and delete much easier. – phpisuber01 Dec 26 '12 at 14:32
  • 3
    @phpisuber01 blanket cover responses like that aren't useful. – Ja͢ck Dec 26 '12 at 14:43
  • related: http://stackoverflow.com/questions/348363/what-is-the-best-practice-for-storing-uploaded-images – Kzqai Jan 11 '15 at 16:09

1 Answers1

7

A broad overview of what I would typically do:

  1. Store the files themselves in the file system, not in the database. Databases are good at storing data, file systems are good at storing files. Better to use each one for the things they are good at, even if you could do it differently (my opinion).

  2. Store the files outside of your web root. That will make it much easier to control access to them.

  3. Since they are outside your web root, you now can't link directly to the files, so create a script to serve the files themselves. You would pass in a file identifier of some sort from your database to the script, the script would look up the actual path to the file in the database, then serve up the contents of the file. The script could also do user access checks if necessary.

Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
  • Re #3, it might be worthwhile to check out [an earlier answer](http://stackoverflow.com/questions/10596116/caching-http-responses-when-they-are-dynamically-created-by-php/10596231#10596231) to reduce processing time in php when serving files. – Ja͢ck Dec 26 '12 at 14:41
  • Also, while this approach is most frequently applied, it would help to list the pros and cons. – Ja͢ck Dec 26 '12 at 14:45
  • Maybe a quick explanation of this magical script - specifically if the file is not accessible directly from a page, how would it be accessible from the said file lookup script. – Andrew Jan 26 '17 at 17:38
  • @Andrew - this would be a server side script, not javascript. So it should be able to access whatever files are available to the user account that the web server is running on (depending on which language/web server you are using server side of course) – Eric Petroelje Feb 06 '17 at 20:12