开发者

Redirect a user after the headers have been sent

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

Is there any way开发者_Go百科 (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?


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;
}


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.


You can use Javascript or a Meta tag. But if you do not want to fix your code to display output after processing then just turn on output_buffering in the .htaccess file for the site.

php_flag output_buffering on

Is what you would put in your .htaccess file to turn that on. It will allow redirects even if you output stuff while processing. This is because the output buffer saves the buffer to the end, so no data is sent prior to.


Maybe you can use the output buffer before you make a decision to redirect the page.

IMHO otherwise there is only the way to use HTML meta redirect or JavaScript redirect.


This is the php function i use to redirect. If headers haven´t been sent, uses "header(location)", else, uses javascript function.

 function redirect($url)
{
    $baseUri=_URL_;

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

        echo $string;
    }
    else
    {
    if (isset($_SERVER['HTTP_REFERER']) AND ($url == $_SERVER['HTTP_REFERER']))
        header('Location: '.$_SERVER['HTTP_REFERER']);
    else
        header('Location: '.$baseUri.$url);

    }
    exit;
}


PHP doe not offer any other way as far as I remember (limitation of the http protocol), but you can do this with javascript, but it is a completely different process : with js, it is the content of the page that tells the browser to perform a redirection, not the server.


In my case worked ob_start

Javascript solution looks so.. strange

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜