Reputation: 452
I am running a website, and part of the site is allowing users to upload files to a SQL database, and then download them. The download itself works, but the file is getting corrupted. Image files cannot be opened, doc files are showing up as blank. I will attach below my uploading script and my downloading script.
$classid = $_POST['uploadclass'];
$userid = $_SESSION['id'];
$view = $_POST['view'];
$filename = $_FILES['uploadfile']['name'];
$tmpname = $_FILES['uploadfile']['tmpname'];
$filesize = $_FILES['uploadfile']['size'];
$filetype = $_FILES['uploadfile']['type'];
$fp = fopen($tmpname, 'r');
$content = fread($fp, filesize($tmpname));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc()){
$filename = addslashes($filename);
}
$query = "INSERT INTO uploads VALUES('','$filename', '$filetype', '$filesize', '$content', '$userid', '$classid', '$view', 'no')";
$run = mysqli_query($connect, $query);
mysqli_close($connect);
header('location: files.php');
Below is the code for my download page.
$query = "SELECT * FROM uploads WHERE id=$id";
$run = mysqli_query($connect, $query);
while ($row = mysqli_fetch_assoc($run)){
$name = $row['name'];
$type = $row['type'];
$size = $row['size'];
$content = $row['content'];
}
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
?>
Upvotes: 0
Views: 397
Reputation: 70893
You are incorrectly handling the files and everything else when inserting them into the database. All files that are already there are damaged and probably destroyed.
addslashes()
is no escaping function for a database. Always use the escaping function that comes with the DB extension you are using. If you are using mysqli, then the correct function must be mysqli_real_escape_string()
.
You should however have a look at prepared statements. These will use an different way of transferring the data that does not need escaping. Do pay attention however to the setting of magic quotes. The preferred setting is OFF, and the recent PHP versions starting with 5.4 have this feature removed already. So you have to deal with escaping the data you insert into the database anyway.
Upvotes: 1