Devin_Kinh
Devin_Kinh

Reputation: 61

Whats the best way to keep a user signed in after their session ends?

I'm working on a simple login page for a class and was planning on using cookies to keep users logged in (if they choose) after closing their browser. I used a checkbox input button as a case to set a cookie. After a user goes to the login page and signs in I send them to a script to check for valid username and passwords where I also check if the button was used

  #QotD.php

  if(isset($_GET['signed_in']))      #check box value
  if($_GET['signed_in']=="on"){ 
  if(isset($_GET['username']))
    $username = $_GET['username'];
    setcookie('username',$username,time()+10000);#cookie set with username
  }

What I thought to do was to have a conditional statement at the beginning of the login page file checking whether a cookie is set and if it is go directly to the main page.

#QotD_homepage.php
if(isset($_COOKIE['username'])){
header("Location: main_page.php");
exit();
}

The problem is that it seems to keep the user signed in whether they check the box off or not. I tried adding a button to unset the cookie but it didn't work. Is there a more efficient way to handle cookies in this manner?

Upvotes: 0

Views: 565

Answers (2)

Jack
Jack

Reputation: 685

Firstly, for signing in a user, you are going to want to use the POST action method as it hides the information from the url. The GET method contains the information in the url and can be easy copied and hacked.

Secondly, you if statements should look like this

if(isset($_GET['username']))
{ 
  $username = $_GET['username'];
  # do something with username...
  if(isset($_GET['signed_in']) && $_GET['signed_in']=="on")
    setcookie('username',$username,time()+10000);
  }
}

To solve your question regarding why user is being logged in every time, even when you don't set the cookie, the reason is probably because you have not unset the cookie. This is usualy done via a logout page.

Create a logout page with the code:

setcookie('username', null, 1);

Then run this page every time you wish to unset the cookie to test the login without ticking the checkbox.

Hope it helps :)

Upvotes: 2

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

If conditional statement is wrong.Fix it by ending it with end if or using {} brackets. Use the code below

<?php
  if(isset($_GET['signed_in'])) {     #check box value
  if($_GET['signed_in']=="on"){ 
  if(isset($_GET['username']))
    $username = $_GET['username'];
    setcookie('username',$username,time()+10000);#cookie set with username
  }
}
?>

OR

<?php
  if(isset($_GET['signed_in'])) :     #check box value
  if($_GET['signed_in']=="on"){ 
  if(isset($_GET['username']))
    $username = $_GET['username'];
    setcookie('username',$username,time()+10000);#cookie set with username
  }
endif;
?>

Hope this helps you

Upvotes: 1

Related Questions