是否可以在readfile()之后重定向页面?
Is it possible to redirect a page after a readfile()?
I tried to use Header, but that doesn't work. Also the meta redirect doesn't work either:
header ("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$file");
header("Content-Length: $size");
readfile($file_path); // Giving file to the customer
// header('Location:../checkout.php'); Doesn't work
// echo ('<meta http-equiv="refresh" content="1;url=../checkout.php">'); Doesn't work
是否可以在readfile()之后重定向页面? p>
我试图使用Header,但这不起作用。 元重定向也不起作用: p>
header(“Content-Type:application / pdf”);
header(“Content-Disposition:attachment; filename = $ file“);
header(”Content-Length:$ size“);
readfile($ file_path); //将文件提供给客户
// header('Location:../ checkout.php'); 不起作用
// echo('&lt; meta http-equiv =“refresh”content =“1; url = .. / checkout.php”&gt;'); 不起作用
code> pre>
div>
It's impossible to output the header after you have output the file. Headers need to go first (hence the name). If you would output the header before you output the file, a browser would be free to ignore the body. I'm not sure what browsers actually do, but I doubt both a redirect and a file download will be initiated simultaneously. One or the other would probably be ignored.
Basic fact: You cannot output any information apart from what's necessary for the file download in the same response as the file download. The header of the file download response can only contain information regarding the file, the response body can only contain the file (i.e. no <meta>
refreshes or such, those would become part of the file).
To illustrate, this would be what the browser receives:
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename=foo
Content-Length: 42
woieufhm23umh29… (file contents as binary gibberish) …cQ3985fno1rHtn3f
qo8923r10d30<meta http-equiv="refresh" content="1;url=../checkout.php">
Everything after the first blank line would be saved as the file contents, including the <meta>
tag. You would actually corrupt the file by outputting any additional content there.
The way this usually works is to present the user with a "download page", which has an auto-refresh meta tag and/or Javascript, which first initiates the download, then on the second refresh redirects.
Your code immediately sends the file contents to the user, i.e. it starts a download.
If you want to start the download and display another page, display the page and - on this page - send this header: header('Refresh: 2;url=url/to/your/download');
As the browser will start a download it will not redirect away from the displayed page.
I had a workaround. The page where I send the file I opened with a target="_blank"
, on first page I did a onclick javascript redirect or show div.
The page that opens to send the file, starts the download and inmediatly closes.
Hope this helps.