Sudi Sudi - 7 months ago 31
PHP Question

PHP: How to make browser to download file on click

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 working. I want to download files when i click on the hyperlink download. Selected the path from MySQL database.

$rows = mysqli_num_rows($result);

if($rows>0)
{

while($row = mysqli_fetch_assoc($result))
{
?>
<div> <?php echo $row['Object_Name'];?>
<a href="<?php
$file_url = $row['Object_Path'];
header('Content-Type: application/octet-stream');
header("Content-disposition: attachment; filename=\"".$row['Object_Name']. "\"");
readfile($file_url);
?>">Download</a><br>
</div>
<?php
}

}

Answer

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 :)