Reputation: 2203
I have this customer that saves files as base64 into a MEDIUMBLOB field (please don't ask why).
The files is saved like this:
$file = file_get_contents($_FILES['file']['tmp_name']);
$file = base64_encode($file);
$file = mysql_real_escape_string($file);
$file_name = mysql_real_escape_string($_FILES['file']['name']);
$file_ext = mysql_real_escape_string($_FILES['file']['type']);
$sql = "INSERT INTO $file_table_name (file, file_name, file_ext) VALUES ('$file', '$file_name', '$file_ext')";
This is the code I'm using to force download the file:
header('Content-type: ' . $data->file_ext);
header('Content-Disposition: attachment;filename="' . $data->file_name . '"');
echo base64_decode($data->file);
die();
For some reason, this works fine with PDF files, but not image files. When I try to open the file in Windows Preview it says: "Windows Photo Viewer can't open this picture because the file appears to be damaged, corrupted or is too large". The original file is ~150KB.
If I do this;
echo '<img src="data:' . $data->file_ext . ';base64,'.$data->file.'" />';
die();
...the image looks fine and I'm able to save the image (save as) without issues.
Anyone know what I'm doing wrong? Am I missing any headers?
Update with values from the DB:
file_name: 'test.png'
file_ext: 'image/png'
file: https://gist.githubusercontent.com/horgen/25298f2689d9aed865db/raw/gistfile1.txt
The original file: http://cl.ly/image/2o3X3u3a0V0S
The encoded file: http://cl.ly/image/1S3K3v0x0U0p
Upvotes: 2
Views: 11065
Reputation: 2203
Yeah.. This is akward.. I found the problem. This is a Wordpress site and I have this functions.php file where I include all my functions. For some reason the previous developer on this project included a php file inside functions.php. The included file had some whitespace/tab before the "php"-tag and this generated a newline in the decoded file :S
Anyways, thank you all for trying to help me :)
Upvotes: 1
Reputation: 853
You could try
echo base64_decode(str_replace(' ', '+', $data->file));
See the PHP manual page for base64_decode() and also the comments on the page.
Upvotes: 1