在会话结束后保持用户登录的最佳方式是什么?

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

我正在为 class 开发一个简单的登录页面,并计划使用 cookie 让用户在关闭浏览器后保持登录状态(如果他们选择)。我使用复选框输入按钮作为设置 cookie 的案例。用户进入登录页面并登录后,我将他们发送到脚本以检查有效的用户名和密码,我还检查按钮是否被使用

  #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
  }

我想做的是在登录页面文件的开头有一个条件语句,检查是否设置了 cookie,如果设置了则直接转到主页。

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

问题在于,无论用户是否选中该框,它似乎都让用户保持登录状态。我尝试添加一个按钮来取消设置 cookie,但它没有用。有没有更有效的方式来处理cookie?

If 条件语句是 wrong.Fix 它以 end if 结尾或使用 {} 括号。使用下面的代码

<?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
  }
}
?>

<?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;
?>

希望对您有所帮助

首先,为了登录用户,您需要使用 POST 操作方法,因为它隐藏了 url 中的信息。 GET 方法包含 url 中的信息,很容易被复制和破解。

其次,您的 if 语句应该如下所示

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);
  }
}

要解决您关于为什么用户每次都登录的问题,即使您没有设置 cookie,原因可能是因为您没有 unset cookie。这通常通过 logout 页面完成。

使用以下代码创建注销页面:

setcookie('username', null, 1);

然后 运行 每次您希望取消设置 cookie 以测试登录而不勾选复选框时,此页面。

希望对您有所帮助:)