I have a small form where my users are able to upload a a file into MySQL and then later it can be downloaded. It appears that my files are being uploaded successfully, but when I try to download them, I get the error “Cannot open file, it may be corrupt”. My upload script is:
$fileName = $_FILES['proposal']['name'];
$tmpName = $_FILES['proposal']['tmp_name'];
$fileSize = $_FILES['proposal']['size'];
$fileType = $_FILES['proposal']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
include './lib/configdb.php';
include './lib/opendb.php';
$query = "INSERT INTO appfiles (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
include './lib/closedb.php';
}
and the download script is as follows:
<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
include './lib/configdb.php';
include './lib/opendb.php';
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM appfiles WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
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;
include './lib/closedb.php';
exit;
}
?>
<body>
<?php
include './lib/configdb.php';
include './lib/opendb.php';
$query = "SELECT id, name FROM appfiles";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
echo " <a href=\\"download.php?id=$id \\"> $name </a> <br>";
echo "benchmark 1";
}
}
include './lib/closedb.php';
?>
</body>
</html>
Any assistance on why the files are becoming corrupted after being uploaded and how to remedy this would be helpful.