I have 3 files:
config.php
<?php
$db = new PDO("mysql:host=localhost;dbname=datarepo", "root", "");
?>
data.php (the data repository which displays the table of files from my database)
<?php
<table class ="table">
<thead>
<tr>
<th>#</th>
<th>File</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
include('config.php');
$stmt = $db -> prepare("SELECT * FROM files");
$stmt->execute();
while($row = $stmt->fetch()){
?>
<tr>
<td> <?php echo $row["id"]?></td>
<td> <?php echo $row["name"]?></td>
<td><a href="download.php?id=<?php echo $row["id"]?>" class="btn btn-primary">Download</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
?>
download.php
<?php
include "config.php";
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $db -> prepare("select * from files where id=?");
$stmt->bindParam(1,$id);
$stmt->execute();
$data = $stmt -> fetch();
$file = 'dpo'.$data['name'];
if(file_exists($file)){
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Type:'.$data['mime']);
header ('Content-Length:'.filesize($file));
readfile($file);
exit;
}
}
?>
When I try to download a file from the data repository (data.php), I will be brought to an empty page but no file will be downloaded, with the url: http://localhost/dpo/download.php?id=1
Here is a sample of the 'files' table from the 'datarepo' database in mySQL.
My question is, how do I get the file(s) to be downloaded? I know uploading files to the database is not recommended but for this project I am required to do so.
For reference, here's my upload.php (please ignore the file sanitation for now):
<?php
include('config.php');
if(isset($_POST["submitfile"])) {
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$data = file_get_contents($_FILES['file']['tmp_name']);
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('csv','doc','docx','jpg','pdf','png');
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 5000000){
$stmt = $db ->prepare("insert into files values('',?,?,?,?)");
$stmt ->bindParam(1,$fileName);
$stmt ->bindParam(2,$fileType);
$stmt ->bindParam(3,$fileSize);
$stmt ->bindParam(4,$data);
$stmt ->execute();
echo "File uploaded successfully.";
}
else {
echo "File size is too big.";
}
} else {
echo "There were was an error uploading the file.";
}
} else {
echo "File format not supported.";
}
}
?>