views:

59

answers:

2

Hi, i am just wondering if there is a way of setting up different "content-type" when downloading through php? like .mp3 AND .pdf etc.. instead of having to specify just one file type. My problem is that i have 2 file types to be downloaded, one type is pdf and the other type is mp3, but if i change the "content-type" to audio/mpeg, then it doesn't show the extension for the .pdf... i hope you understand? please help!

A: 

This function works great for me:

function Download($path, $speed = null)
{
    if (is_file($path) === true)
    {
     set_time_limit(0);

     while (ob_get_level() > 0)
     {
      ob_end_clean();
     }

     $size = sprintf('%u', filesize($path));
     $speed = (is_null($speed) === true) ? $size : intval($speed) * 1024;

     header('Expires: 0');
     header('Pragma: public');
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     header('Content-Type: application/octet-stream');
     header('Content-Length: ' . $size);
     header('Content-Disposition: attachment; filename="' . basename($path) . '"');
     header('Content-Transfer-Encoding: binary');

     for ($i = 0; $i <= $size; $i = $i + $speed)
     {
      echo file_get_contents($path, false, null, $i, $speed);

      while (ob_get_level() > 0)
      {
       ob_end_clean();
      }

      flush();
      sleep(1);
     }

     exit();
    }

    return false;
}

You can also optionally specify the max speed at which the file is delivered.

Alix Axel
+2  A: 

If you mean your user is downloading some content that's sent from a PHP script, which is also sending the Content-type HTTP header, can you not set that header with a different value for each type of file ?

Something like this (pseudo-code) :

if (file is a PDF) {
    header('Content-type: application/pdf');
} else if (file is a MP3) {
    header('Content-type: audio/mpeg');
}

And a "default" case might be useful, if you also have some other files you have not thought about just yet.

Pascal MARTIN