How do I download a file based on it’s ID? Right now I have an upload script that timestamps all files as they reach the server. I can’t use the $_FILES[file][‘name’] global to retrieve the files by name since they’re all uniquely named.
Here’s what my upload code looks like:
$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
// Adding timestamp with image's name so that files with same name can be uploaded easily.
$mainFile = $targetPath.date("Y-m-d H-i-s").'-'. $_FILES['file']['name'];
//get variables for database
$projectname=$_POST['projectname'];
$version= $_POST['version'];
$comments=$_POST['comments'];
if(move_uploaded_file($tempFile,$mainFile)){
include 'db.php';
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, version, comments, created)
VALUES ('$FileName', '$file_type','$projectname','$version','$comments', NOW())");
echo "Your file ". basename( $_FILES['file']['name']). " has been successfully uploaded and recorded in the database!";
}
else {
echo "Your file failed to upload.";
}
}
Here’s what the view code looks like. As you can see the download link is just a blank HREF right now.
Error_Reporting(0);
include("db.php");
//Show all files
$result = mysql_query("SELECT * FROM myversions ORDER by projectname ASC, created DESC");
echo "<div class='table-responsive'>";
echo "<table class='table table-striped table-bordered'>";
echo "<thead>";
echo "<tr>";
echo "<th>File Name</th><th>Project Name</th><th>Version</th><th>Comments</th><th>Created</th>";
echo "</tr></thead>";
echo "<tbody>";
while($row = mysql_fetch_array($result)){
$id = $row['id'];
echo "
<tr>
<td>$row[filename]</td>
<td>$row[projectname]</td>
<td>$row[version]</td>
<td>$row[comments]</td>
<td>$row[created]</td>
<td><a href='#'>Download File</a></td>
</tr>";
}
echo "</tbody>";
echo "</table>";
echo "</div>";
//close connection
mysql_close($conn);
I know I should do something like:
$id = $row['id'];
and pass it like:
<a href ='download.php?id=$id'>Download</a>
Not sure how to finish it off though.