amir amir - 19 days ago 6
PHP Question

Is it possible to redirect a page after a 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

Answer

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.