Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best redirect methods? [closed]

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();
        }
    }
}
like image 781
JasonDavis Avatar asked May 22 '26 05:05

JasonDavis


1 Answers

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).

like image 108
Kornel Avatar answered May 24 '26 18:05

Kornel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!