8

Ok so i have this code that will allow a user to download a song

$file = DIR_DOWNLOAD . $download_info->row['filename'];
$mask = basename($download_info->row['mask']);
$mime = 'application/octet-stream';
$encoding = 'binary';

if (!headers_sent()) {
if (file_exists($file)) {
    header('Pragma: public');
    header('Expires: 0');
    header('Content-Description: File Transfer');
    header('Content-Type: ' . $mime);
    header('Content-Transfer-Encoding: ' . $encoding);
    header('Content-Disposition: attachment; filename=' . ($mask ? $mask : basename($file)));
    header('Content-Length: ' . filesize($file));
    $file = readfile($file, 'rb');

The problem is that if the song has a space in it like sinsita happy 1 SONIFI.mp3 the user will only download a text file named sinsita ...any ideas how to fix this behavior

Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • See http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http – Emre Yazici Jun 29 '11 at 03:04

1 Answers1

12

You have to quote the file name in the content disposition:

header('Content-Disposition: attachment; filename="' . ($mask ? $mask : basename($file)) . '"');

Edit: Now that also means that if the file name contains a quote; then you have to escape that quote. So really your code looks like this now:

header('Content-Disposition: attachment; filename="' . str_replace('"', '\\"', ($mask ? $mask : basename($file))) . '"');
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • this worked great but in chrome its not even downloading...but in safari and firefox its working perfect...any ideas – Matt Elhotiby Jun 29 '11 at 03:15
  • @Tamer: I don't think that is related to this issue. What happens if you remove the `filename` all together? (Smoke testing to see if that is the issue) – vcsjones Jun 29 '11 at 03:16
  • Small note: I used double quote in the header with single quotes wrapping the filename, that didn't work. Quote usage should be as the answer above. – Martijn Jan 31 '14 at 15:32