PHP Header Content-Disposition: attachment forces .php file or inline

19,822

Solution 1

I think filesize($track) is wrong, it should be the whole path filesize("/home/user/gets/".$track). This would cause php to output error messages, preventing you from setting the content-length and disposition header.

Solution 2

Try taking the quotes off the filename:

header('Content-Disposition: attachment; filename=test.mp3');
                                                  ^^^^^

Getting the name of the script instead of the filename you're trying to use is generally a sign that the filename contains invalid characters for the filesystem the browser's trying to save to. e.g. " isn't permitted.

Share:
19,822
rubio
Author by

rubio

Updated on June 04, 2022

Comments

  • rubio
    rubio almost 2 years

    I want to download a single .mp3 file from my site but when using this code it forces a .php in Firefox and Safari. But in chrome it will send force the file as inline and play on the page. How can i get them to actually download a .mp3 file?

    $track = $_SERVER['QUERY_STRING'];
    
    if (file_exists("/home/user/gets/" .$track)) {
        header("Content-Type: audio/mpeg");
        header('Content-Length: ' . filesize($track));
        header('Content-Disposition: attachment; filename="test.mp3"');
        $str = "/home/user/gets/".$track;
        readfile($str); 
        exit;
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
        echo "no file";
    }
    

    I have also tried to download a .zip file as well and changing the Content-Type to application/ocetet-stream but it forces .php files on all browsers.

    //$track = $_SERVER['QUERY_STRING'];
    $track = 'testfile.zip';
    if (file_exists("/home/user/gets/" .$track)) {
        header("Content-Type: application/octet-stream");
        header('Content-Length: ' . filesize($track));
        header('Content-Disposition: attachment; filename="test.mp3"');
        $str = "/home/user/gets/".$track;
        readfile($str); 
        exit;
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
        echo "no file";
    }