I am working on a site where people can upload and download files. I have the upload working the way I want it to and the download to the folder works too. The only issue I am having is finding a way to download a single file and not all of the. The code below is for the download from the Server/database.
// Downloads files
if (isset($_GET['file_id'])) {
$id = $_GET['file_id'];
// fetch file to download from database
$sql = "SELECT * FROM files WHERE id= $id";
$result = mysqli_query($conn, $sql);
$file = mysqli_fetch_assoc($result);
$filepath = 'uploads/' . $file['name'];
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('uploads/' . $file['name']));
readfile('uploads/' . $file['name']);
// Now update downloads count
$newCount = $file['downloads'] + 1;
$updateQuery = "UPDATE files SET downloads=$newCount WHERE id=$id";
mysqli_query($conn, $updateQuery);
exit;
}
}
The code below is the code for the PHP/HTML site where all the files are displayed and allows the user to download the files. I only want to list one file and to have the option to put link to any file not all of them. I can get a single file to download if I change the $sql = "SELECT * FROM files WHERE id= $id" to a number like 7 or any id number but it still still displays all the other files yet still only downloads the file for ID 7 on each link.
<thead>
<th>ID</th>
<th>Filename</th>
<th>size (in mb)</th>
<th>Downloads</th>
<th>Action</th>
<tr>
<td><?php echo $file['id']; ?></td>
<td><?php echo $file['name']; ?></td>
<td><?php echo floor($file['size'] / 1000) . ' KB'; ?></td>
<td><?php echo $file['downloads']; ?></td>
<td><a href="downloads.php?file_id=<?php echo $file[$id]? >">Download</a> </td>
</tr>
If someone could let me know what I'm missing I would be truly grateful.