Uploading/Downloading files stored in MySQL database

Posted on 16th Feb 2014 by admin

Hey all,

This problem just came up in my website and I'm having a hard time figuring out what's wrong. I have a intranet portal running (custom built) and I'm storing all different types of documents in a mysql database. Previously, I was able to read the contents of the file into the DB and then pull it out and the file would open just fine. Now, for some reason, everything except PDF files come across as gibberish.

I've gone ahead and tried to upload files that I know are working, I've switched from base64_encode to addslashes, tried to do a mysql COMPRESS and UNCOMPRESS when uploading a new file....nothing. I'm just not sure why all of a sudden this stopped functioning properly (haven't done any upgrades to the server, db or code)

Anyone have any ideas I can try?

For reference, the code for inserting and downloading follows:
insert:

case "Add File":
$fp = fopen($_FILES['userfile']['tmp_name'], 'r');
$content = fread($fp, filesize($_FILES['userfile']['tmp_name']));
$content = base64_encode($content);
mysql_query("INSERT INTO intranet.documents(id, type, contents, content, name, category, updated) VALUES ('', '".$_FILES['userfile']['type']."', '".$content."', COMPRESS('".$content."'), '".addslashes(str_replace(" ", "_", strtolower($_FILES['userfile']['name'])))."','".$_POST['category']."', '".date("Y-m-d H:i:s")."')") or die(mysql_error());
fclose($fp);
redirect("?action=".$_GET['action']);
break;


download:

$_SESSION['content'] = NULL;
$result = mysql_query("SELECT name, type, contents FROM intranet.documents WHERE ID = '".$_GET['id']."'") or die(mysql_error());
$_SESSION['content'] = base64_decode(mysql_result($result, 0, "contents"));
header("Content-Disposition: attachment; filename=".mysql_result($result, 0, "name")."");
header("Content-type: ".mysql_result($result, 0, "type"));

Other forums