Skip to content
Advertisement

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?

Advertisement

Answer

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;
}
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement