Forum Moderators: coopster
I am using this PHP code to upload word docs, rtf's, pdf's and text docs into a mysql db.
<form enctype="multipart/form-data" action="processuploadinsert.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<? echo MAX_FILE_SIZE;?>" />
<!-- Name of input element determines name in $_FILES array -->
Upload this file: <input name="userfile" type="file" />
<input type="submit" value="Upload File" />
</form>
and the processuploadinsert file:
include 'dbconn.php';if($_FILES['userfile']['size'] > 0)
{
$valuesAR['name'] = $_FILES['userfile']['name'];
$tmp_name = $_FILES['userfile']['tmp_name'];
$valuesAR['size'] = $_FILES['userfile']['size'];
$valuesAR['type'] = $_FILES['userfile']['type'];
$fp = fopen($tmp_name, 'r');
$content = fread($fp, filesize($tmp_name));
$valuesAR['content'] = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()) $fileName = addslashes($fileName);
$newID = processInsertArray($nodupefield,'upload',$uppercasefield,$valuesAR,$insertmsg);
if (!$newID) echo $insertmsg;
/*
Table [upload]
uploadID int(11) (Auto) No
name varchar(75) Yes
type varchar(10) Yes
size varchar(10) Yes
content mediumblob Yes
*/
else echo "<p>File $fileName uploaded with newID $newID</p>";
}
The uploads appear to be working correctly, as I'm getting the right filetype and filesizes inserted into the database.
Here is the code to download the blob from the database:
$thisID = $_REQUEST['id'];
if($thisID)
{include 'dbconn.php';
$row = getRow('upload',$thisID); //$row['fieldname']
$type = $row['type'];
$size = $row['size'];
$name = $row['name'];
$content = $row['content'];
header("Content-type: $type");
header("Content-length: $size");
header("Content-Disposition: attachment; filename=$name");
header("Content-Description: PHP Generated Data");
echo $content;
/*
Table [upload]
uploadID int(11) (Auto) No
name varchar(75) Yes
type varchar(10) Yes
size varchar(10) Yes
content mediumblob Yes
*/
};
When I click on the link to call the download file, I am prompted to open or save the document, which is fine. Then, if it's a word or rtf document, I get a "File Conversion Window" box that wants me to "Select the encoding that makes your document readable."
My database field is mediumblob, and I didn't think I need to do anything other than that to upload binary. What am I missing? I've spent 2 days looking for an answer, and can't find anything.
Thanks!
Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.
fopen [php.net]