views:

53

answers:

2

How do i automaticly start a file for download when a user clicks a link? For example when a user clicks a link that allows them to download a image.

Like it works on www.iStockphoto.com

+2  A: 
<a href="path-to-file.jpeg">link</a>

Along with a content-disposition header that makes it an attachment.

David Dorward
THis is the correct answer. (No more +1 left today)
Laykes
COuld you give me an example of the content-disposition header? Can i change this header with PHP?
jamietelin
@jamietelin — There is an entire section of the spec I linked to marked "Examples", and yes, you can change it with PHP (although you would then have to manually pass the rest of the data for the file)
David Dorward
A: 

Here is the answer I was looking for. Hopefully it will help other people looking for an answer.

Create a file called downloadfile.php for example and add the following;

$file = $_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('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }

Then you can add a link to that file like this:

<a href="downloadfile.php?file=dog.jpg">Download image!</a>

Of course this is just an example. It can be done in various ways. Important syntaxes to remember are header() and readfile()

jamietelin
That was already answered. Just set content-disposition header to attachment. That's all. The remnant is optional.
BalusC
I know, its my own question. Just wanted to make the answer more clear. Not everyone enjoy reading 11 pages of text :) (Also in David Dorward answer i find this a bit confusing; <a href="path-to-file.jpeg">link</a>
jamietelin