CancelImage Upload

How to initiate an automatic file download with PHP headers

Here is how you automatically start a file download once a user enters onto a page. Note, the user of course has to be willing to download the file, and can choose not to. If you are looking to force some software onto your visitors you are in the wrong place. If instead however you are looking for a simple download on load for an install shield for instance, carry on reading.

First of all, and most importantly, since the following download is initiated through headers you need to place this code right at the top of your page's code. Not among it, or at the start of an included file, but right at the top.

So, let's proceed to check out the code itself:

<?php

//Download Name can differ from real physical name:

header("Content-Disposition: attachment; filename=DownloadName.doc");

header("Content-Type: application/octet-stream");

//Here the real path and filename are needed:

header("Content-Length: ".filesize("path/file.doc"));

header("Pragma: no-cache");

header("Expires: 0");

$fp = fopen("path/file.doc", "r");

print fread($fp, filesize("path/file.doc"));

fclose($fp);

exit();

?>

And that is all there is to it. As long as you have defined your paths and filenames correctly, your users should be able to download the specified files without a problem!

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com