Content-Disposition with 302 redirect

2020-02-07 03:34发布

问题:

This was working last night, but I must have accidentally changed something, because it isn't now.

What I am trying to do should be clear from these headers:

Content-Disposition: attachment;filename=english_customizable.xml
Location: http://tortoisewrath.com/files/2.xml

However, when this header is sent, the Content-Disposition part doesn't work after the redirect.

...Why?

回答1:

What you're trying to do is inadvisable check this question; Header Location + Content Disposition

Content-Disposition + Location header

But you can do it, to make it work you will have to buffer your whole response before sending it. You can do this with output buffering

  • http://php.net/manual/en/book.outcontrol.php

Else the browser may interpret the Location header before the file is downloaded. It's sketchy either way, so you shouldn't want to do this.

Please note that forcing 'save as' using Content-Disposition: attachment; will make sure the client doesn't go/navigate anywhere, so the method below on its own should be fine in any case.

Streaming a file in php

To just quote a guy who has his brains in the right place:

// To use header() with 'content-type', why don't you use mime_content_type() function rather than checking the type on the basis of extension? 
// Example code: 

<?php 
$file="test.docx"; 
header("Pragma: public"); 
header('Content-disposition: attachment; filename='.$file); 
header("Content-type: ".mime_content_type($file)); 
header('Content-Encoding: identity'); 
ob_clean(); 
flush(); 
readfile($file); 
?> 

// Use $file to map to whichever type of file. 
// Note: the mime types should already be defined in apache settings

Source: http://www.php.net/manual/en/function.header.php#107581

Note that the original answer used Content-Transfer-Encoding which doesn't actually exist in HTTP. The comment below that source explains it: http://www.php.net/manual/en/function.header.php#107044