How to go about making sure a user has logged in
Posted: Sun Apr 19, 2009 8:44 pm
I've made a few additions to my site that I would like only a few people to see / use. I'm using a static log-in until I learn SQL and generally get better with PHP. The code in the first window below is just a login form that checks to see if the user has entered the correct information if so ' $_SESSION['valid'] = true; '. I use this session variable in my other page called loggedin.php to see if it is false then header("Location: login.php"); But nothing is working because i can enter in anything and it will just show me that page. I can also just go to the page I wish the user not to see until they log in even though $_SESSION['valid'] = false;
Please help or possibly just lead me to the right way to handle logging in or keeping track of that kind of stuff.
Please help or possibly just lead me to the right way to handle logging in or keeping track of that kind of stuff.
Code: Select all
<?php
session_start();
// variable used to tell whether user logged in with correct info
$_SESSION['valid'] = false;
//var
$bool1 = false;
$bool2 = false;
$pass_error = false;
$user_error = false;
if (isset($_POST['username']) && isset($_POST['password'])) {
// user entered something
if ($_POST['username'] = "admin") {
// username correct
$bool1 = true;
}
else {
$user_error = true;
}
if ($_POST['password'] = "password") {
// password correct
$bool2 = true;
}
else {
$pass_error = true;
}
if ($bool1 = true && $bool2 = true) {
// both username / password correct - redirect
$_SESSION['valid'] = true;
header("Location: loggedin.php");
}
else {
echo "login.php";
}
}
else {
// user hasn't entered anything
?>
<h1 align="middle">Login</h1> <?php
}
?>
<html>
<body>
<form method="post" action="<?php echo "login.php"; ?>">
<table border="1" align="center">
<tr><td>Username: </td><td><input type="text" name="username" /></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" /></td></tr>
<tr><td><input type="submit" value="login" /></td></tr>
</form>
<?php
if ($pass_error) {
// if true user has entered wrong pass
echo "/n/n wrong password /n";
}
if ($user_error) {
// if true user has entered wrong user
echo "/n/n wrong username /n";
}
?>
</table>
</body>
</html>Code: Select all
<?php
session_start();
if ($_SESSION['valid'] = true) {
// user should be here
echo "<h1>Welcome user " . session_id() . "</h1>";
}
else {
// redirect because user has not logged in
}
?>