Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a file from a PHP server via a website [closed]

I have physical files which I want users to download on my website. The files are located at:

C:/xampp/htdocs/myfile/uploads/*

I need a PHP script which can download files dynamically on click. Let's say I have the following button which when clicked it triggers magic.php script.

<a href="magic.php?file=name"> Download file </a>

What PHP code do I need in magic.php to download the file name I passed in the query parameters?

like image 306
Matthew Barbara Avatar asked Dec 10 '25 18:12

Matthew Barbara


1 Answers

Download link

<a href="magic.php?file=<?php echo urlencode($row['name']); ?>">Download</a>

magic.php page

<?php
$file = 'C:/xampp/htdocs/myfile/uploads/'.urldecode($_GET['file']);

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>
like image 57
Simone Nigro Avatar answered Dec 13 '25 07:12

Simone Nigro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!