Jun 12, 2013
kalpesh

PHP redirect without header()

It’s very frustrating when you want to redirect from one page to another, and you get the error:

Warning: Cannot modify header information – headers already sent by (output started at /some/filename.php:12) in /some/filename.php on line 99

The problem is Headers are already sent, or in simple language the output is already sent to browser when your header() function is called. The best solution is not to pass headers (send html/output to browser) till the point header() function is fired.

Another way is to use output buffering. Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script. For using this method, you have to start your file with ob_start(); so that output gets buffered.

But what if you don’t care whether the output is sent or not, you anyway want the redirect to work? This simple function will do the trick for you. It will check if headers are not sent, then it will call the PHP’s header function to redirect. But if the headers are sent, it will use Javascript to redirect to the URL you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function redirect($url)
{
    if (!headers_sent())
    {
        header('Location: '.$url);
        exit;
    }
    else
    {
        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;
    }
}

1 Comment

  • I’ve tried using the redirect function – and yes, it overcomes the problem of moving to the next screen – but it would appear the session variables are not maintained

Leave a comment

 

Welcome to my Blog

Kalpesh MehtaHelping Magento developers in their day-to-day development problems since 2011. Most of the problems and solutions here are my own experiences while working on different projects. Enjoy the blog and don't forget to throw comments and likes/+1's/tweets on posts you like. Thanks for visiting!

Certifications