I need to print out all the files that I\'ve saved in a database and then make it possible to download them. I am able to echo them, but I don\'t know how to make a download \"b
I once made a similar script, what you have to do is set some headers and echo the data from database.
An example of that could be, assuming that the data is in $row['filedata']
, the following
<?php
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$row['Ime']);
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
echo $row['filedata'];
?>
Now you have to know what file to download first, and for that we can use a GET or POST parameter
<?php
$fileID = htmlentities($_GET['fileID']);
$conn = mysqli_connect('localhost','root','usbw','down');
$fileID = mysqli_real_escape_string($conn, $fileID); // ALWAYS ESCAPE USER INPUT
$query = "SELECT * FROM datoteka where `ID`=$fileID";
$result = mysqli_query($conn, $query);
$result_check = mysqli_num_rows($result);
if($result_check > 1 || $result_check < 1){ //If more then 1 result die
die('inavlid ID');
}
$row = mysqli_fetch_assoc($result);
//and here the above mentioned lines
?>
The easiest way to add a download button to the page would be by using the window.open() function in JavaScript like so:
echo $row['Ime']."<button onclick='window.open(\"download.php?fileID=".$row['ID']."\");'>Download</button><br>";
This will open a new window which will download the file
The total would look something like this For download.php:
<?php
$fileID = htmlentities($_GET['fileID']);
$conn = mysqli_connect('localhost','root','usbw','down');
$fileID = mysqli_real_escape_string($conn, $fileID); // ALWAYS ESCAPE USER INPUT
$query = "SELECT * FROM datoteka where `ID`=$fileID";
$result = mysqli_query($conn, $query);
$result_check = mysqli_num_rows($result);
if($result_check > 1 || $result_check < 1){ //If more then 1 result die
die('inavlid ID');
}
$row = mysqli_fetch_assoc($result);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".$row['Ime']);
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
echo $row['filedata'];
?>
and for index.php
<?php
$conn = mysqli_connect('localhost','root','usbw','down');
$query = "SELECT * FROM datoteka";
$result = mysqli_query($conn,$query);
$result_check = mysqli_num_rows($result);
if($result_check > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['Ime']."<button onclick='window.open(\"download.php?fileID=".$row['ID']."\");'>Download</button><br>";
}
}
?>
You can read here https://www.php.net/file_put_contents, and you need to know where the path file is. ex:
/users/john/downloads/namefile.doc