I am attempting to store files in a MySql database based upon this article. Before you suggest I store files on the file system and not in the database the files uploaded will be stored and relate to records in the database. I could keep a path to the files and just the file names but I want users to be able to modify and delete the files directly through the web interface. So, let’s just pretend that storing in the database is a good option and not discuss others.
My issue is when I go to download the file the data returned from the BLOB in the MySql database is not exactly what I uploaded in test. If I use the function of addslashes then binary wise it is completely off. If I remove that function from the routine then I get much closer.
Using a Binary Diff application I can see that, while not using addslashes the file data returned has one additional byte of data at the beginning of the file and in turn one less byte at the end. The remainder of the file’s data is offset by one due to this little feature of the download.
I am using a FORM to submit the data and enctype is set to multipart/form-data as it should be. Here’s some code I’m using to get it all to work. DAL in the code references a class I created for my Data Access Layer. It handles all saving and retrieving routines and doesn’t seem to be injecting any new data. I’ve checked by looking at the file’s content before it goes to my DAL class for saving and the extra byte is already there.
upload
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fp = fopen($_FILES['userfile']['tmp_name'], 'r');
$_FILES['userfile']['content'] = fread($fp, $_FILES['userfile']['size']);
$_FILES['userfile']['content'] = addslashes($_FILES['userfile']['content']);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$_FILES['userfile']['name'] = addslashes($_FILES['userfile']['name']);
}
$fileDAL = new DAL("files");
$newID = $fileDAL->SaveItem($_FILES['userfile'], false);
echo "<br>File ".$_FILES['userfile']['name']." uploaded as ID $newID<br>";
}
download
if(isset($_GET['id']))
{
$id = $_GET['id'];
$objFiles = new DAL('files');
$objFile = $objFiles->GetItem($id);
header("Content-length: $objFile->size");
header("Content-type: $objFile->type");
header("Content-Disposition: attachment; filename=$objFile->name");
echo $objFile->content;
exit;
}
Turns out that I add an extra line feed or carriage return at the end of a PHP file that was in my headers prior to this code being executed. It caused the header upon writing to include the line feed (OA) in the binary data for file saving.