Redirect after HTTPResponse send.

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
ganga
Forum Newbie
Posts: 1
Joined: Wed Dec 03, 2008 2:01 pm

Redirect after HTTPResponse send.

Post by ganga »

Hi,
How can i redirect to a different page after my download started.
Here is my code.

HttpResponse::setCache(true);
HttpResponse::setContentType('application/octet-stream');
HttpResponse::setContentDisposition("abc.exe", false);
HttpResponse::setFile(realpath('./abc/abc.exe'));
HttpResponse::send();
ob_flush();
flush();
sleep(1);
header("Location: http://yahoo.com"); // here i want to redirect to a page after download started. But this is not working.

How can i do this?

Thanks
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Redirect after HTTPResponse send.

Post by Chris Corbyn »

Redirects work based on HTTP headers themselves.

A full HTTP response looks something like:

Code: Select all

HTTP/1.0 200 OK
Content-Type: text/html; charset="utf-8"
Content-Length: 12
 
Hello World!
 
If the browser processes the headers before it displays the content. Now, in order for a redirect to work you need to set a "Location" header.

Code: Select all

HTTP/1.0 302 Moved
Location: http://site.tld/some-other-place/
 
 
As you can probably see from that concept then, if you've already sent your headers, it's not possible to send the Location header and do the redirect. It would just be a line within the body of the page and would not be interpreted by the browser.

You may possibly be able to cheat by using a multipart document. You'd have to make some drastic coding changes for this to work however since your document needs to be nested inside a parent document:

Code: Select all

HTTP/1.1 200 OK
Content-Type: multipart/x-mixed-replace; boundary="_-_something"
 
--_-_something
Content-Type: text/html; charset="utf-8"
Content-Length: 12
 
Hello World!
--_-_something
Status: 302
Location: http://site.tld/some-other-place/
 
--_-_something--
 
The document consists of two smaller HTTP documents inside itself. I'm not sure the redirect would be interpreted however.

Better off figuring out if you need to redirect before you commit any response to the client ;)
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Redirect after HTTPResponse send.

Post by alex.barylski »

Holy...your alive. I haven't seen you (CC) or K-Hugs in ages and all of a sudden you both show up...what nerve :P

Just teasing :)
Post Reply