I have a simple webpage which allows users to upload files to my website (in a BLOB in the database) and retrieve files. The problem I am having is that the files that are retrieved are corrupt. It seems to work fine (sometimes) with .PDF files, but .DOC files are always corrupt upon download. In fact, it appears that part of the SELECT statement is showing up at the beginning of the downloaded files.
The beginning of the downloaded files-- if viewed in a text editor-- look like this "SELECT name, type, size, content FROM upload WHERE intid = '60'<br>ミマ 爍ア ・ >  ' ) "
I have attached a pic of the database table called "upload" which stores the files"
Here is the form that allows people to upload files (I deleted the other form fields that didn't pertain to the upload):
<form method="post" action="addassignment.php" enctype="multipart/form-data">
<table>
<tr>
<td>Attach a File (optional):</td>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="4000000">
<input name="userfile" type="file" id="userfile">
</td>
</tr>
<tr>
<td width="175">
<p>
</p>
</td>
<td>
<input type="submit" class ="box" value="Send"/>
<input type="reset" value="Reset"/>
</td>
</tr>
</table>
</form>
Here is the snipped of code that checks to see if the person chose to upload a file and writes it to the database:
if(isset($_POST['period']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = mysql_real_escape_string($content);
fclose($fp);
$fileName = str_replace(' ', '', $fileName);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, type, size, content, teacherid, assignmentId) VALUES('" . mysql_real_escape_string($fileName) . "', '$fileType', '$fileSize', '$content', '" . userIDFromDirectory() . "', '$whichAssignmentId')";
mysql_query($query) or die('<br>Error, file upload failed ' . mysql_error());
echo "<br>File <i>$fileName</i> uploaded!<br>";
}
Here is the snippet of code that allows people to download files from the database:
if(isset($_GET['id']))
{
$id = $_GET['id'];
$query = "SELECT name, type, size, content FROM upload WHERE intid = '$id'";
echo $query;
echo '<br>';
$result = mysql_query($query) or die('Error, query failed' . mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=" . $name );
echo $content;
exit;
}
Any suggestions or any other additional information needed??
Thanks so much in advance!