In a PHP file when I need to redirect a user and headers are already sent so I can not use php's header function, in this case which is the best method to redirect a user?
Fastest and most reliable method regardless of the users browser brand?
echo '<script type="text/javascript">window.top.location="http://localhost/";</script>';
// OR
echo '<meta http-equiv="refresh" content="0;url=' .$location. '">';
UPDATE
Here is my end result code I am using now, if headers are already sent where I cannot redirect to the homepage, I just bring the homepage to me, so instead of including the body page, it will include my homepage and footer
function validlogin($url) {
if (!isset($_SESSION['auto_id']) || ($_SESSION['auto_id']=='')) {
$_SESSION['sess_login_msg'] = 'Please login';
$_SESSION['backurl'] = $url;
$temp = '';
if (headers_sent() === false){
header("Location: /");
exit();
}else{
//header is already sent so we will just bring the homepage to us instead of going to it!!!
include 'mainbody.inc.php';
include 'footer.inc.php';
exit();
}
}
}
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
Again, use ob_start();
I would say the second.
If the user has javascript disabled, or uses a browser without javascript, the 1st redirect will never work.
Don't use any of these! You should always use HTTP redirects.
Use ob_start()
to buffer content and avoid problem of headers already sent.
You might also try to write MVC application, where you would know whether you need to redirect before outputting anything (but with ob_start()
that is not necessary).
Piggy back on porneL:
The huge problem with your methods: you kill the back button. Killing the back button is the most irritating thing on the web.
I have never found a need to redirect after headers have been sent. You should probably rethink what you're trying to do.