I want a user to be logged in for years when they register or login to my site.
The session should only be destroyed when they click Logout.
My code doesnt work because the user session seems to be destroyed when they close their browser.
This is my register.php for new users
<?php
session_start();
if(isset($_POST["submit"]))
{
$username = strtolower(trim($_POST["username"]));
$password = strtolower(trim($_POST["password"]));
$password=hash('sha512', $password);
$email = strtolower(trim($_POST["email"]));
$date = time();
$sql = "INSERT INTO users (username,password,email,date) VALUES (:username,:password,:email,:date)";
$q = $conn->prepare($sql);
$q->execute(array(':username'=>$username, ':password'=>$password, ':email'=>$email, ':date'=>$date));
if
($q)
{
$_SESSION["user"]=$username;
setcookie('username', $username, time()+10*365*24*60*60);
setcookie('password', $password, time()+10*365*24*60*60);
header("location:../"); exit();
}
}
?>
Here is my login code
<?php
session_start();
$username = strtolower(trim($_POST["username"]));
$username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$password = strtolower(trim($_POST["password"]));
$password=hash('sha512', $password);
$results = $connecDB->prepare("select username,password from users where username = :username and password = :password");
$results->bindParam(':username', $username);
$results->bindParam(':password', $password);
$results->execute();
$rows = $results->fetch();
if($rows>0) {
$_SESSION["user"]=$username;
setcookie('username', $username, time()+10*365*24*60*60);
setcookie('password', $password, time()+10*365*24*60*60);
header("location: ../");
}
?>
Here is my logout code that destroys the session
<?php
session_start();
$user=$_SESSION["user"];
$username = user_info($user, 'id');
if(!isset($_SESSION['user']))
{
header("Location: ../login/");
}
else if(isset($_SESSION['user'])!="")
{
header("Location: ../");
}
session_destroy();
unset($_SESSION['user']);
header("Location: ../");
?>
Here is my main index page(the page the user is directed to after successful login or after they register)
<?php
session_start();
$user=$_SESSION["user"];
...
?>
Here is my function that I call to check if user is logged in
function isloggedin()
{
session_start();
if(isset($_SESSION["user"])) return true;
else return false;
}