Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

php - Force browsers to download a file rather than open

I'm using typical PHP code to download documents:

  header('Content-Type: ' . $mimeTypes[$fileext]); 
  header('Content-Disposition: attachment; filename="' . $filename . '"');
  header('Content-Transfer-Encoding: binary');
  header('Accept-Ranges: bytes');
  header('Cache-Control: private');
  header('Pragma: private');

  readfile($filepath);

Everything works fine - a download/save-as dialog opens, except for .doc files which attempt to open in docs.google.com but they fail due to lack of permission - that's because I'm serving files from outside a website root.

So how do I bypass docs.google and force every browser to offer save-as dialog regardless of the file mime type? ('doc' => 'application/msword')

I tried the following to no avail:

  1. in .htaccess file:

    <FilesMatch ".(?i:doc)$">
        ForceType application/octet-stream
        Header set Content-Disposition attachment
    </FilesMatch>
    
  2. in .htaccess file:

    AddType application/octet-stream .doc
    
  3. in PHP script:

    header('Content-Type: application/force-download');
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add this to your headers:

header("Content-type: application/force-download");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...