-3

Possible Duplicate:
Headers already sent by PHP

I am getting this error when I try to redirect after running a user login script.

It attempts to change the header data at this line:

header("Refresh: 2; url=index.php");

This is the full login.php script.

<?php 
session_start();
require_once('init.php');

$username = trim($_POST['username']);
// create a new object
$login = new Auth($_POST, $dbh);

    if($login->validateLogin()){

        $_SESSION['loggedin'] = true;
        $_SESSION['username'] = $username;
        $list = $login->getUserInfo();
        $_SESSION['id'] = $list['id'];
        $_SESSION['thumb'] = $list['img_thumb'];

        echo '<div class="content">';
        echo '<h1>Thank you for logging in '.$username.'. Redirecting...</h1>';
        echo '</div>';
        header("Refresh: 2; url=index.php");

    }else{

        echo '<div class="content">';
        echo '<h1>Sorry but we didn\'t recognise those login details, please try again.</h1>';
        echo '</div>';

    }



require_once('inc/footer.inc.php');
?>

The init.php file calls the header.php containing the html5 doctype, meta tags etc.

How can I redirect the user to the index page after logging them in and send the header information as usual?

Community
  • 1
  • 1
crmepham
  • 4,676
  • 19
  • 80
  • 155

3 Answers3

3

From the PHP docs.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

If you want the page to redirect after a few seconds you will need to use Meta Refresh.

<meta http-equiv="refresh" content="5;URL='http://example.com/'">
Baylor Rae'
  • 3,995
  • 20
  • 39
0

Simply move the header() call before any echo statements:

<?php
/* ... */
if($login->validateLogin()){

    $_SESSION['loggedin'] = true;
    $_SESSION['username'] = $username;
    $list = $login->getUserInfo();
    $_SESSION['id'] = $list['id'];
    $_SESSION['thumb'] = $list['img_thumb'];

    header("Refresh: 2; url=index.php"); // Put this *before* any output
    echo '<div class="content">';
    echo '<h1>Thank you for logging in '.$username.'. Redirecting...</h1>';
    echo '</div>';

}else{

    echo '<div class="content">';
    echo '<h1>Sorry but we didn\'t recognise those login details, please try again.</h1>';
    echo '</div>';

}
/* ... */
0b10011
  • 18,397
  • 4
  • 65
  • 86
0

Using echo and then trying to set a header for Location will always raise that error. ¿What could be better to let the user know about redirect than redirecting them? If you want to show such message (this approach would not show it for a whole second if it ever worked), you should use javascript to update content and use some kind of delay...

... but perhaps it's too much work. If you show a welcome message after login, it should be enough, right? :)

Alfabravo
  • 7,493
  • 6
  • 46
  • 82