Storing PDF as blob & downloading

Hi Guys!

I am uploading a PDF file and storing in a MYSQL database as a LongBlob. The PDF is successfully uploaded, but when I try and output the file (download) it just shows a blank PDF file.

Any ideas what could be wrong? Here’s the code.

Upload code:


$fp = fopen($_FILES['pdf_file']['tmp_name'], 'r');
			$content = fread($fp, filesize($_FILES['pdf_file']['tmp_name']));
			$content = addslashes($content);
			fclose($fp);
			
			// Insert into database
			$this->dbh->query("insert into pdfs 
				(userid,pdf_name,pdf_size,pdf_content,updated) 
				values 
				(
				'".mysql_real_escape_string($_POST['client'])."',
				'".mysql_real_escape_string($_FILES['pdf_file']['name'])."',
				'".mysql_real_escape_string($_FILES['pdf_file']['size'])."',
				'".mysql_real_escape_string($content)."',
				now())");

Download code:


header("Content-length: ".$result['pdf_size']);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=".$result['pdf_name']);
echo $result['pdf_content'];

unfortunately I can’t help to debug your code because I don’t normally save pdf, image or any other types of uploaded files directly into a database table.

instead of storing the file contents in the db table what about considering, if you haven’t already done so, storing whatever meta data you like about the file into a db table but storing the uploaded file itself in a separate directory on your server. You would then need to store info relating to the path to the file in the db table as well.

the downsides of storing the file contents in the db table include bloating the size of your table and thus degrading performance.

You’re escaping the PDF file contents using mysql_real_escape_string() which is in turn degrading the result. If you are truly concerned that the PDF might contain a SQL injection attempt, you could always use a base64_encode() instead which will still preserve the contents and avoid any possible injection. Of course you’ll need to do a base64_decode() when echoing the contents.

I’m going to agree with Kalon here on the actual file storage, however I trust that you’ve done your research and would prefer the database blog method.