tags:

views:

47

answers:

3

Im writing a login script. My db.php doesnt echo/print anything so why doesnt header("Location: index.php"); redirect upon successful login? the login info is correct. I know i need to sanitize the input but that is not a problem at the moment.

 <?php
        require('db.php');
        $username = $_POST['un'];
        $password = $_POST['pw'];
        $qry="SELECT uid FROM users WHERE name='$username' AND pass='".md5($password)."'";
        $result=mysql_query($qry);
        if(mysql_num_rows($result) == 1){
            session_regenerate_id();
            $user = mysql_fetch_assoc($result);
            $_SESSION['S_UID'] = $user['uid'];
            session_write_close();
            header("Location: index.php");
            exit();
        }else{
            echo "<center><form action='index.php' name='login'>Login failed! Please try again with correct username and password.<br><input type='submit' name='failed' value='Return to Login'></form></center>";
            exit();
        }
    ?>
+2  A: 

the function header will only work if no output has been sent by the script before the function is called. Check if any codes above has echoed something.

If not, check that the include files above do not have an extra space or newline after the closing "?>" tag. Otherwise this space or newline will be sent to the browser before your header.

iWantSimpleLife
I didn't even think about a whitespace after my /closing/ php tag....i had one.
Dacto
Sorry, if my memory doesnt fail to me... if any output have sent, and you try to modify the header, it will cause php to throw an exception... I think it must be something with the URL that he is redirecting to...
Garis Suero
A common practice I am doing now is to do away with the last PHP closing "?>" at all. the scripts will still run, and there is no danger of that extra space.Another way is to turn on output buffering at the very very top of the file. This will prevent anythings from being sent to the browser until the end of processing (or at least until ob_flush is called).
iWantSimpleLife
A: 

Are you sure no output is being produced anywhere in the script (or db.php)? Not even a few extraneous spaces ?

He/she should be getting errors (ie: headers already sent by) if that was the case. Turn on error reporting (ie: `error_reporting(E_ALL)`)
NullUserException
A: 

Try using the full URL for example:

header("Location: http://www.mysite.com/index.php");

Some browsers (thanks IE) doesn't understand the 301 redirect code with uncompleted URI.

This header location behavior in PHP is a good tool, but easy to be implemented in the incorrect scenario...for this purpose i would consider using require() instead of header(location)

like:

if (!imLoggedIn()){
  require('loginForm.php');
  exit;
}
Garis Suero