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");
?>
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.phpAlso – Another Helpful Tip:
I noticed that you haven’t got an
exit();after yourheader();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.phpAlso – Another Helpful Tip:
You have
You probably want
You will want to show login form if there is no $_SESSION[‘user’]
So your final code would look like this: