7

The question says it all.

How do I let the users download a file from my website and not let them see what link that file comes from?

I understand that there might be a need for something like a download.php which will serve as the gateway but past that phase, I dont know what to script next...

If it bothers you to write the whole code, a few function names that I should need to use would be really handy!

Eugene Mihaylin
  • 1,736
  • 3
  • 16
  • 31
Registered User
  • 8,706
  • 9
  • 32
  • 40

4 Answers4

10

Find a way to identify the file to download (for instance, a GET variable that matches the ID of a row in a database, or something along these lines). Make damn sure it's a valid one, because you don't want your users to be able to download anything off your site. Then, use header with Content-Disposition to tell the browser the file should be downloaded, and readfile to output it.

For instance:

<?php

$id = intval($_GET['id']);
$query = mysql_query('SELECT file_path FROM files WHERE id = ' . $id);
if (($row = mysql_fetch_row($query)) !== false)
{
    header('Content-Disposition: attachment; filename=' . basename($row[0]));
    readfile($row[0]);
}
exit;

?>
zneak
  • 134,922
  • 42
  • 253
  • 328
  • I remember using a similar technique for exporting email addressess in a csv file. The content-type header was ignored by safari for mac. – Benbob Jul 15 '10 at 05:15
  • Is this script htaccess-proof? I have a htaccess rule to deny the access to real URL in case the method was bypassed. Does `deny from all` affects this script too? –  Dec 28 '16 at 19:36
  • @CodigosTutoriales, rules in .htaccess files only impact web requests from a client. They don't do anything to prevent your server code from reading files on the server. – zneak Dec 28 '16 at 19:39
4

You can't make someone download a file from a URL without letting them know the URL. It's not possible under the HTTP specification. Anything downloaded has a URL.

You can, however, have a download URL that only works once, or requires some specific information to be passed via the POST method. You check for a token in the GET or POST variables and invalidate that token once it's used once.

thomasrutter
  • 114,488
  • 30
  • 148
  • 167
1

You can use the header() function which is documented here

I would suggest scrolling down and looking at the 1st example. It seems to be doing exactly what you want.

Josh
  • 10,961
  • 11
  • 65
  • 108
Josiah
  • 4,754
  • 1
  • 20
  • 19
  • Just a note for Shedo Chung-Hee Surasi - The second example also shows you how you can specify a filename that is different from the name of the original file (as you mentioned in your question). – jerebear Jul 15 '10 at 04:27
0

readfile should do what you want. Put the actual file outside the web server root, and require some credentials before passing back the file.

drawnonward
  • 53,459
  • 16
  • 107
  • 112