Johnny97 Johnny97 - 1 year ago 119
PHP Question

Force download from protected folder

I have a .htaccess locked folder with .pdf files. No I want to provide a button and when the user clicks on it it will force the download. I've tried a lot with readfile() but can't create this because I don't have the knowledge.

<a href="" onClick="force the file download" class="button plans-download">Download</a>

Please help me I don't have any idea to make this and I am despairing.

Answer Source
$file = file_get_contents('PATH TO FILE ON SERVER');
$size = strlen($file);
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Content-Type: application/pdf'); ## This needs to be updated to the proper file type. EDIT: PDF added.
header('Content-Length: ' . $size);
echo $file;

This will start the download in the browser. You never expose the directory by keeping the files somewhere on the server that is not accessible by the web server. However, PHP will read the file on the disk and then push it to the browser. Moreover, you can arbitrarily set the file name that you send the user. I would recommend using md5(rand() . microtime()) as the file name, and then the user will never be able to find the URL again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download