views:

62

answers:

1

I've got a really simple login script using PHP's sessions to limit access, but I'm having a really peculiar issue. The login always fails on the first attempt, even with correct credentials, but second and subsequent attempts work with no issues. I'm really confused as to the cause, so any help would be appreciated.

the login form, with non-relevant code removed (yes, I'm aware that storing the login stuff inside the PHP file as plain text is normally a bad idea, but it's not relevant in this case):

<?php

$username = $_POST['username'];
$password = $_POST['password'];

$valid_user = "user";
$valid_password = "password";


if (($_POST['op'] == "ds") && ($username == $valid_user) && ($password == $valid_password)) {
    session_start();
    session_register('valid');
    $_SESSION['valid'] = 'yes';
    header("Location: valid.php");
}

?>

<p>Username:<br>
<input type="text" name="username" size=15 maxlength=25></p>
<p>Password:</strong><br>
<input type="password" name="password" size=15 maxlength=25></p>
<input type="hidden" name="op" value="ds">
<p><input type="submit" name="submit" value="login"></p>

and every page that needs authenications has

require "auth.php"

auth.php:

<?php

session_start();

if($_SESSION['valid'] != 'yes') {
    header("Location: login.php");
}

?>
+2  A: 

Try a die() after

header("Location: valid.php");

it could be that that gets ignored because you're outputting the login form to the browser immediately afterwards.

Additionally, a die() is mandatory after

header("Location: login.php");

if your script outputs anything following it. Otherwise, the requesting client could receive sensitive information even if it is not logged in.

Pekka
Neither of those fixes seem to work, unfortunately. The issue seems to be that the $_SESSION['valid'] variable fails to get set properly, because if I remove the "header("Location: login.php")" and try to echo $valid, it outputs a blank line.
sslepian
@sslepian can you put the `session_start` into the head section of all scripts?
Pekka
Apparently, moving session_start out of the if statement and into the top of the login form fixed the issue. Thanks!
sslepian