Uploading, Saving and Downloading Binary Data in a MySQL Database
Pages: 1, 2, 3
Creating the download scripts
First let's create the script to show the list of files currently in our table, and then we can start working on the script to download the files.
This should create a clean and beautiful table with all the files on the table. For a real world application, you would probably want to limit the number of files displayed here, and also do some formatting on the filesize and filetype fields. I'll leave that as an exercise for the reader.
Let's go to the download script now. It's really simple, and it is going to work with any type of file inside the database. Whenever users click on the "Download" links, a download dialog should open with the filename coming from the database.
View contents of download.php.
Sometimes in other scripts, text files (.txt) or even images are shown in the browser window, instead of opening the download dialog. That's because of the HTTP header "Content-Disposition:," which needs to have something recognizable as the first argument. If you put a recognizable MIME type in there, such as an image MIME type, the browser will try to open it in the window. The same goes for text files or any other filetype that the browser can recognize.
A lot of times people ask how they could track the number of downloads for each file. This script can be easily changed to track the "hits," and you could even create an extra script to show statistics of each file.
Have fun and keep writing!
Joao Prado Maia is a web developer living in Houston with more than four years of experience developing web-based applications and loves learning new technologies and programming languages.
Discuss this article in the O'Reilly Network Forum.
Return to the O'Reilly Network Hub.
