0

I have this PHP function for redirect page:

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

Now, when i submit form if form not have error redirect to another page. now i have 2 problem :

  • after post submit and when page is redirect i see blank page and then page redirected! how do redirect page without see blank page?
  • i need to show success message in new page. how do handle success error to new page ?

how do fix this errors?

Pink Code
  • 1,802
  • 7
  • 43
  • 65
  • Why are you not using PHP's redirect funtion in the else part as well? Why to go for Javascript/HTML redirect ? – addicted20015 Oct 04 '14 at 09:30
  • @addicted20015 that is beacause you sometimes get an error `headers already send`. This is a workaround that error – SuperDJ Oct 04 '14 at 09:34
  • 2
    _how do redirect page without see blank page?_ That's impossible. JS redirect will be done only on page load completion. While the page is not loaded you (visitor) see current page rendering i.e. blank page in your case. But you can insert some text to html informing about redirect is in process, e.g. "Wait a minute" – hindmost Oct 04 '14 at 09:37
  • 1
    I dont understand why a workaround should be needed in the first place? A redirect is meant to be sent before sending any headers and one can easily place such checks before sending any data/headers. – Pawan Oct 04 '14 at 09:38

1 Answers1

0

If you use a javascript or html refresh redirect, you will always see a blank page. The best solution is to display a message on the page saying that they will be redirected shortly. In your case showing a success message and that they'll be redirected.

Ideally you should never need the js or html redirect. If it's an issue, find a way to rearrange the code so that the redirect happens before any other code is run. And make sure there are no errors causing it.

As for showing a success message on the page the user was redirected to, there's another Stack Overflow Answer that addresses it. The simplest solution in my opinion is to add a GET variable to the end of the url.

header('Location: '.$url.'?success=1'); 

On redirected page

if ( isset($_GET['success']) && $_GET['success'] == 1 )
{
     echo "Success";
}

An alternative solution is to use a session variable. See link to stack overflow question above.

Community
  • 1
  • 1
David Hobs
  • 4,351
  • 2
  • 21
  • 22