Forcing to download a file using PHP

前端 未结 10 1122
借酒劲吻你
借酒劲吻你 2020-11-22 04:04

I have a CSV file on my server. If a user clicks on a link it should download, but instead it opens up in my browser window.

My code looks as follows



        
10条回答
  •  猫巷女王i
    2020-11-22 04:22

    Here is a more browser-safe solution:

        $fp = @fopen($yourfile, 'rb');
    
        if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
    {
        header('Content-Type: "application/octet-stream"');
        header('Content-Disposition: attachment; filename="yourname.file"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header("Content-Transfer-Encoding: binary");
        header('Pragma: public');
        header("Content-Length: ".filesize($yourfile));
    }
    else
    {
        header('Content-Type: "application/octet-stream"');
        header('Content-Disposition: attachment; filename="yourname.file"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: ".filesize($yourfile));
    }
    
    fpassthru($fp);
    fclose($fp);
    

提交回复
热议问题