Uploading, Saving and Downloading Binary Data in a MySQL Database
Pages: 1, 2, 3
Creating the upload scripts
To make thing easier, I created an open_db.inc
include file, so I don't have to keep using the same code to connect to a server and select the database. I'm a lazy programmer, and you should be one too!
This next script is used to upload a new file into the database. We always have to check the variable ($binFile
) for contents. Whenever someone just hits "Upload" without selecting a file, the file input field variable will hold "none". We also have to make an extra security check on the binary content itself, since it can contain some weird characters that need a slash. This can break our SQL statement, so we addslashes()
it!
We are using the same script to handle both actions: uploading a new file and showing the form to add the information related to this new file. The hidden input field called MAX_FILE_SIZE
on the form is needed so the client side can limit the filesize of new files. Also, don't forget to add the extra attribute ENCTYPE="multipart/form-data"
to your form, or else your script is not going to work at all.
Okay, that seemed almost too easy, right? Now what we need to do is create the download script, as well as the script that shows the list of files currently in the database.
Next page: Creating the download scripts
