开发者

best way redirect/reload pages in PHP

Whats the best way to reload/redirect a page in PHP which completely r开发者_JS百科emoves all history/cache? Which headers should I use?

What happens:

On clicking a link, get-parameters is set and a script is executed. When finished, I want to redirect and reload the page without the get-parameters. At first, it looks like nothing has happened, but when pressing F5, the changes appear.

What I want:

Redirect and reload so the changes appear without pressing F5.


header('Location: http://www.example.com/', true, 302);
exit;

Ref: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

edit:

This response is only cacheable if indicated by a Cache-Control or Expires header field.


function redirect($url) {
    if(!headers_sent()) {
        //If headers not sent yet... then do php redirect
        header('Location: '.$url);
        exit;
    } else {
        //If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo '</noscript>';
        exit;
    }
}

// How to use
$url = "www.google.com";
redirect($url);


The best way to reload a page and force it to be not taken from the cache will be to append a random id or timestamp to the end of the url as querystring. It makes the request unique each time.


Try this:

echo '<script>document.location.replace("someurl.php");</script>';

This should replace browser history but not cache.


header('Location: http://example.com/path/to/file');


just for information, related to SEO:

301 would tell search engine to replace url in their index. so if url1 is redirecting to url2 with 301, all major search engine [google, yahoo + bing] would replace url1 with url2.

302 works in different way. It says the url is located temporarily in some other address.

see this post


<?php
header('Cache-Control: no-store, private, no-cache, must-revalidate');     // HTTP/1.1
header('Cache-Control: pre-check=0, post-check=0, max-age=0, max-stale = 0', false);  // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');                  // Date in the past  
header('Expires: 0', false); 
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header ('Pragma: no-cache');
header("Location: https://example.com", true, 302);
exit();
?>


The safest way is to use a Header Redirect

header('Location: http://www.example.com/', true, 302);
exit;

But beware, that it has to be sent BEFORE any other output is sent to the browser.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜