I've been using a session login script for several weeks... and now I'm trying to add a checkbox for "keep me logged in".
I've added <input type="checkbox" name="remember">
to my form and these two lines of code to my login script:
$_POST['user'] = stripslashes($_POST['txt_user']);
$_SESSION['user'] = $_POST['txt_user'];
if(isset($_POST['remember'])){
setcookie("cookname", $_SESSION['user'], time()+60*60*24*100, "/");
And now my login script works, but only if the "keep me logged in" box is checked... if I leave the box unchecked, the session is not set, when I submit the login form, I'm right back at the login again. In theory, I'd like the cookie set only if the username and password check out.
Here's the entire login code:
<?php
// we must never forget to start the session
session_set_cookie_params (0, '/', '.domain.com');
session_start();
MySQL_connect("localhost", '****', '*****'); MySQL_select_db("users");
$errorMessage = '';
if (isset($_POST['txt_user']) && isset($_POST['txt_pass'])) {
$user = $_POST['txt_user'];
$pass = $_POST['txt_pass'];
// check if the user id and password combination exist in database
$sql = "SELECT user
FROM users
WHERE user = '$user' AND pass = PASSWORD('$pass')";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
}
/* Username and password correct, register session variables */
$_POST['user'] = stripslashes($_POST['txt_user']);
$_SESSION['user'] = $_POST['txt_user'];
if(isset($_POST['remember'])){
setcookie("cookname", $_SESSION['user'], time()+60*60*24*100, "/");
if (mysql_num_rows($result) == 1) {
// the user id and password match,
// set the session
$_SESSION['logged_in'] = true;
// after login we move to the main page
if ($_GET['redir']) {
header('Location: '.$_GET['redir']);
} else {
header('Location: welcome.php');
exit;
}
} else {
$errorMessage = 'Sorry, not a valid combination - please see below';
}
}
?>
Am I missing something as simple somewhere? Remember, I'm a nOOb.
Thank you.
~Wayne