PHP Sessions - User not stored after login

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");
?>

Answers


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();
?>

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.


Need Your Help

Draggable pin not updating coordinates in Google Maps API

javascript google-maps google-maps-api-3

I have this code that allows users to insert pins in Google Maps, by clicking on the map. Now I'm trying to make this pin draggable, so I just added draggable:true, in the initialization of the

how to retrieve particular datas from html page in objective c

iphone html objective-c

I am new to iPhone development. I want to display data taken from inside a html table from a web page. Is there any way to retrieve the data from the table in the html page? Html page is the source...