Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect a user after the headers have been sent

Tags:

I understand that so long as data has been sent to the browser then the headers cannot be modified.

Is there any way (using PHP) that I can perform a redirect to take a user to another page (obviously not using headers)

If so could you please point me to some documentation?

like image 910
GaryDevenay Avatar asked Aug 15 '11 15:08

GaryDevenay


People also ask

How do you fix Cannot redirect after HTTP headers have been sent?

If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location. replace or location. href, etc.) to redirect to whatever URL you want.

What happens to headers on redirect?

In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3 , and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header.


2 Answers

Decided to write my own php function which implements a javascript redirect. See the code below.

function redirect($url)
{
    $string = '<script type="text/javascript">';
    $string .= 'window.location = "' . $url . '"';
    $string .= '</script>';

    echo $string;
}
like image 73
GaryDevenay Avatar answered Sep 28 '22 07:09

GaryDevenay


I assume output buffering is not an option, since you mention that data has been sent. Use meta redirects, or output JavaScript that takes care of this.

The former could be implemented by adding the following to the <head> section

<meta http-equiv="refresh" content="0; url=http://example.com/">

For the latter, writing something like the following could help:

<script type="text/javascript">
    window.location = "http://example.com/";
</script>

Replace http://example.com/ with your target URL. Note that the latter might be more wieldly to implement if some data has indeed been sent.

A caveat: Both these methods can be blocked at the client end, but technically, so can 301 and 302 redirects.

like image 44
susmits Avatar answered Sep 28 '22 06:09

susmits