PHP Beginner. File uploading is successful but my browser doesn\'t download the files, instead it reads the file. So i referred other threads and found below code which is not w
You have to use two separate files.
In link page, you can output a HTML like this:
<a href="http://www.example.com/download.php?file=1">Download file 1</a>
<a href="http://www.example.com/download.php?file=2">Download file 2</a>
<a href="http://www.example.com/download.php?file=3">Download file 3</a>
(...)
You can use a <form>
, if you prefer.
Then, in download.php:
Select appropriate file using GET/POST parameter ($_GET['file']
in above example);
send appropriate headers (like in your original code);
echo your file (you can use readfile
);
Mandatory: no additional output in this script! Even a single additional space will corrupt downloaded file.
In a paged called download.php, have the following code:
<?php
$filename = 'file.pdf';//this should be the name of the file you want to download
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
?>
Your main page should then have a link to the download page like this:
<a href="download.php">DOWNLOAD</a>
Let me know if that works for you.
Edited:
My previous example was for the download of a pdf file. In the case that you want to download a different type of file, a few lines have to be slightly modified. I recommend you first try downloading a pdf file with the previous code, and after having accomplished that testing out on other files.
To retrieve the path from the database, you can use MySQL (PDO).
$sqlStatement = "SELECT path FROM my_table WHERE some_id = ".$something;
/*if you are retrieving the path from the database,
you probably have a lot of different paths available
there, so only you know the criteria which will decide
which of the many paths it is that you choose to extract*/
$sqlPrepared = $connection->prepare($sqlStatement);
$sqlPrepared->execute();
$row_info = fetch($sqlPrepared);
$filename = $row_info['path'];// this would be the $filename = 'file.pdf'
//that was in the example above
If you are not sure how to connect to the database, there are a lot of articles online explaining MySQL that is relatively straightforward.
I hope that helped :)