Display message before redirect to other page

HTTP refresh redirect to wait 5 seconds:

header('Refresh:5; url=login6.php');
echo 'Please Log In First';

You can't do it that way. PHP header must sent out before any content, so the correct order is:

header("location: login6.php");
echo "Please Log In First";

But these codes will redirect instantly and wouldn't let you see the content. So I would do the redirection by JavaScript:

echo "Please Log In First";
echo "<script>setTimeout(\"location.href = 'http://www.example.com';\",1500);</script>";

A redirect is a redirect ;-)

If you tell a browser by using a Location: header to redirect to another page, the browser does just this: It redirects to the other page. And the browser does this immediately - without any delay.

Therefore, your echo won't display at all.

Set headers first

Furthermore, you need to set headers before each other output operation (as pointed out by Fred -ii-):

// First, echo headers
header("location: login6.php");

// Then send any other HTML-output
echo "Please Log In First";

Better not use auto-redirects

Quite likely, you won't show a message and then - after a certain amount of time - automatically redirect to another page. People might get confused by this process. Better do this:

Show the login-page and present a user-hinter or error-message on this page.

General solution

Prepare a component in the user's session, that contains information to be displayed at the next script instance. This component might be a list of messages like this:

$_SERVER[ 'sys$flashMessagesForLater' ] = array(
  "Sorry, userID and password didn't match.",
  "Please login again."
);

Each time a script request comes in, check if $_SERVER[ 'sys$flashMessagesForLater' ] is a non-empty array.

If this is the case, emit these values to a well-defined located on the generated HTML-page. A well-defined location would always be at the same location, somewhere at the top of each page. You might probably wish to add a read box around error messages.

You might want to prepare a class like this:

class CFlashMessageManager {

  static public function addFlashMessageForLater( $message ) {

    $_SERVER[ 'sys$flashMessagesForLater' ][] = $message;

  }

  static public function flashMessagesForLaterAvailable() {

    return isset( $_SERVER[ 'sys$flashMessagesForLater' ] )
        && is_array( $_SERVER[ 'sys$flashMessagesForLater' ] )
        && ( 0 < count( $_SERVER[ 'sys$flashMessagesForLater' ] ))
        ;

  }

  static public function getFlashMessageForLaterAsHTML() {

    return implode( '<br />', $_SERVER[ 'sys$flashMessagesForLater' ] );

  }

} // CFlashMessageManager

You can use header refresh. It will wait for specified time before redirecting. You can display your message then.

header( "refresh:5; url=login.php" ); //wait for 5 seconds before redirecting

Tags:

Php