44

Is it possible to let your user download a file with a different name?

For example, there is a file called "4324ffsd34.jpg". I want people to download it via download.php, with a different name (like "filetodownload.jpg"), without renaming the original file.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Utku Dalmaz
  • 9,780
  • 28
  • 90
  • 130
  • You can also do this in Apache with mod_rewrite without needing to hit your PHP scripts. May not be applicable to your situation, but if it is, it could improve performance. – Artelius Oct 27 '09 at 01:34

5 Answers5

71

Sure, use a Content-disposition header

header('Content-Disposition: attachment; filename="filetodownload.jpg"');

if you wish to provide a default filename, but not automatic download, this seems to work.

header('Content-Disposition: filename="filetodownload.jpg"');
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
David Snabel-Caunt
  • 57,804
  • 13
  • 114
  • 132
  • yes i can see now, thx :), but i guess i must also use "readfile('original.pdf');" to do it – Utku Dalmaz Oct 27 '09 at 01:25
  • Absolutely, and good to set the Content-Length and Content-Type too. You can use filesize() for the length and write your own function based on the extension to do content-type or use http://uk2.php.net/fileinfo – David Snabel-Caunt Oct 27 '09 at 01:28
  • @RULE101 you can either use `readfile()` or `fread()` to do it – RJ Anoop Jul 24 '15 at 03:43
31

Sure you can, just try something like this:

$original_filename = '4324ffsd34.jpg';
$new_filename = 'my_new_filename_is_detailled.jpg';

// headers to send your file
header("Content-Type: application/jpeg");
header("Content-Length: " . filesize($original_filename));
header('Content-Disposition: attachment; filename="' . $new_filename . '"');

// upload the file to the user and quit
readfile($original_filename);
exit;

Hope it helps!

Frankie
  • 24,627
  • 10
  • 79
  • 121
29

There is also another way if you are using html5

<a href="link/to/my/file/with/a/name/i/dont/like.jpg" download="MyFile.jpg">Download</a>

Cheers :3

The Bumpaster
  • 944
  • 7
  • 20
3

Nothing wrong with the above but I had to add:

ob_clean();
flush();

before readfile

otherwise I can not open the download jpg/png file

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
3
<a href="4324ffsd34.jpg" download="filetodownload">Download</a>
Gayan Dasanayake
  • 1,933
  • 2
  • 17
  • 22