views:

58

answers:

3

I am building a basic password protected area on my website and I have a login form.

<!-- login.php -->
<?php
session_start();
?>
<?php if(!empty($_SESSION['user'])) { ?>
<form>
    <input type="text" name="username" />
    <input type = "password" name = "password" />
    <input type="submit" value = "login" />
    <input type="hidden" name="token" value="KdasS2wFgw24F7hh" />
</form>
<?php } else { ?>
You are already logged in.
<? } ?>


<!-- dologin.php -->

<?php
$allowed = //sql checking db
if($allowed > 0) {
    $_SESSION['user'] = $row['user_id'];
}
header("Location: login.php");
?>
+9  A: 

You have missed the session_start() at the top of your dologin.php. It is required at the top of each page before any output has started.

Without session_start(); you won't have access to create or update a session variable (In your case $_SESSION['user'])

session_start() : http://php.net/manual/en/function.session-start.php

Also - Another Helpful Tip:

I noticed that you haven't got an exit(); after your header(); You will need this so that if the user refreshes the login.php after login the browser won't resubmit the posted data to dologin.php

Also - Another Helpful Tip:

You have

<?php if(!empty($_SESSION['user'])) { ?>

You probably want

<?php if(empty($_SESSION['user'])) { ?> // No `!`

You will want to show login form if there is no $_SESSION['user']

So your final code would look like this:

<!-- login.php -->
<?php
session_start();
?>
<?php if(empty($_SESSION['user'])) { ?>
<form>
    <input type="text" name="username" />
    <input type = "password" name = "password" />
    <input type="submit" value = "login" />
    <input type="hidden" name="token" value="KdasS2wFgw24F7hh" />
</form>
<?php } else { ?>
You are already logged in.
<? } ?>


<!-- dologin.php -->

<?php

session_start();

$allowed = //sql checking db
if($allowed > 0) {
    $_SESSION['user'] = $row['user_id'];
}
header("Location: login.php");
exit();
?>
Lizard
A: 

I think you have a marker too much in your if-else statement.

<?php if(!empty($_SESSION['user'])) { ?>

means if the the session-user is NOT empty, then display the input forms, else display the text "Your are alreday logged in". I think this results in that you will always display the text and never get to the login form. Dispose the (!) marker, and your up and running again

<?php if(empty($_SESSION['user'])) { ?>

ref: PHP empty()

BennySkogberg
A: 

You're checking if (!empty($_SESSION['user'])), but before they've logged in, $_SESSION['user'] should be empty. In which case, they'll get the message "You are already logged in." instead of a login form, but since there's no form, there's nothing to check, so there's no way to log in.

cHao