I have made a login that works for sessiosn but not cookies.. here is my login.php code
<?php
include 'functions.php';
if(loggedin()){
header("Location: index.php");
exit();
}
if(isset($_POST['login'])){
$username=$_POST['username'];
$password=$_POST['password'];
if(isset($_POST['rememberme'])) {
$rem=$_POST['rememberme'];
} else { $rememberme=""; }
if($username&&$password){
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
while($row = mysql_fetch_assoc($login)){
$db_password = $row['password'];
if($password == $db_password){
$loginok= TRUE;
}
else{
$loginok= FALSE;
}
if($loginok==TRUE)
{
if($rememberme=="on"){
setcookie("username",$username, time() + 7200);
}else if ($rememberme==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
else
die("Incorrect Username/Password");
}
}
else
die("Please enter a username and password");
}
and my functions.php
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$db = "loginphp";
mysql_connect($host, $user, $pass) or die("Couldn't connect");
mysql_select_db($db);
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}
}
but when I close the broswer the cookie does not save and it acts as if i've logged out completely. sessions work fine..
here is my logout.php as well
session_start();
session_destroy();
setcookie("username","",time() - 7200);
header("Location: login.php");
It seems like you're setting $rem, rather then $rememberme. Change the line to:
$rememberme = $_POST['rememberme'];
Just to warn you though, with this method if someone wanted to log in, all they'd have to do is set a username in a cookie and bingo!
Have a look at the accepted answer here for a good method.
While I'm at it, you also need to protect yourself against SQL injection attacks, which your current code is open to. Look here .
I changed the format for your cookie to allow it to live for 30 days, no matter what you should always verify data in set duration of time. You assigned the $_POST to $rem not $rememberme so I corrected your function:
if($loginok==TRUE)
{
if($rem=="on"){
setcookie('username', $username, time() + (60 * 60 * 24 * 30)); // expires in 30 days
}else if ($rem==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
I suggest you rethink how you are dealing with the remember me logins, perhaps you should come up with a hash that you can store in an encrypted format in the cookie and verify it on the server side. This "hash"
should change at each visit etc.. just a recommendation.
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.