Forcing to download a file using PHP

前端 未结 10 943
借酒劲吻你
借酒劲吻你 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条回答
  • 2020-11-22 04:37

    This cannot be done reliably, since it's up to the browser to decide what to do with an URL it's been asked to retrieve.

    You can suggest to the browser that it should offer to "save to disk" right away by sending a Content-disposition header:

    header("Content-disposition: attachment");
    

    I'm not sure how well this is supported by various browsers. The alternative is to send a Content-type of application/octet-stream, but that is a hack (you're basically telling the browser "I'm not telling you what kind of file this is" and depending on the fact that most browsers will then offer a download dialog) and allegedly causes problems with Internet Explorer.

    Read more about this in the Web Authoring FAQ.

    Edit You've already switched to a PHP file to deliver the data - which is necessary to set the Content-disposition header (unless there are some arcane Apache settings that can also do this). Now all that's left to do is for that PHP file to read the contents of the CSV file and print them - the filename=example.csv in the header only suggests to the client browser what name to use for the file, it does not actually fetch the data from the file on the server.

    0 讨论(0)
  • 2020-11-22 04:44

    Or you can do this using HTML5. Simply with

    <a href="example.csv" download>download not open it</a>
    
    0 讨论(0)
  • 2020-11-22 04:44

    This means that your browser can handle this file type.

    If you don't like it, the easiest method would be offering ZIP files. Everyone can handle ZIP files, and they are downloadable by default.

    0 讨论(0)
  • 2020-11-22 04:47

    Nice clean solution:

    <?php
        header('Content-Type: application/download');
        header('Content-Disposition: attachment; filename="example.csv"');
        header("Content-Length: " . filesize("example.csv"));
    
        $fp = fopen("example.csv", "r");
        fpassthru($fp);
        fclose($fp);
    ?>
    
    0 讨论(0)
提交回复
热议问题