Forum Moderators: coopster
At the moment users can login and they stay logged in as long as their browser is open.
Now i want to add a checkbox to the login form.
When they check the checkbox they stay logged in for 1 week.
I guess i have to do this with a cookie but i don't have an idea how to do this exactly.
I could use url rewriting but i'd rather use a cookie.
can anyone give me a comprehensive example please.
grtz
The setcookie [uk.php.net] function is what you need. So, an example would be:
<input type="checkbox" name="cookie" value="1">
When you process your form:
if (isset($_POST['cookie']))
{
setcookie("cookie_name", '1', time()+60*60*24*30);
}
This example sets the cookie expiration at 30 days. ie:
60 (1 Min) x 60 = 1hr X 24 = 1 Day X 30 = 30 days.
You can use anything for the variable, here I just used a number. Once set, check the cookie is set using the superglobal $_COOKIE.
if (isset($_COOKIE['cookie_name']))
{
// Ok, this person is logged in
}
To clear the cookie use:
setcookie("cookie_name", "");
Hope that gets you started.
dc
when the user logs in:
if ($paswoord_db === md5($password)) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
session_write_close();
//make cookie if checkbox is enabled
if (isset($_POST['stayloggedin'])) {
setcookie("username", $_SESSION['username'] , time() + 2419200);
setcookie("password", $_SESSION['password'] , time() + 2419200);
}
header('location:index.php');
}
in index:
//login cookie section
if (isset($_COOKIE['username']) && isset($_COOKIE['password']) && $_COOKIE['username']!= '' && $_COOKIE['password']!= '') {
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['password'] = $_COOKIE['password'];
}
//check if user is logged in
if (isset($_SESSION['username']) && isset($_SESSION['password']) && $_SESSION['username']!= '' && $_SESSION['password']!= '') {
echo 'Welcome <span style="font-weight:bold;">' . $_SESSION['username'] . '</span>';
echo ' ¦ <a href="logout.php" style="text-decoration:none; color:white;">logout</a>';
}
else {
echo 'you are not logged in.';
}
it works perfectly but now the password is saved as clear text in the cookie.
I'm having a weird feelign about this.
Or is this this a good way?
grtz