dreamy1992 2015-10-08 04:45
浏览 55
已采纳

一起使用Session和Cookies记住我

In my login page I am using Session and Cookies both, session for usual login and cookies when remember me is checked. My code for creating session or setting cookies is:

if(isset($_POST['login'])){ 
$username = $_POST['user_login'];
$password = $_POST['password_login'];
$stmt = $db->prepare("SELECT * FROM userss WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_db = $row['username'];
$pass_db = $row['password'];
if($username == $user_db && $password == $pass_db) {  
    $_SESSION['username']=$username;
    if ($_POST['rememberme']!=NULL) {
        setcookie('username', $username,time()+31556926);
    }
    header("Location:main.php");
}

and then on any page to create a user fuction I am calling session or cookie like this:

if(isset($_COOKIE['username'])||isset($_SESSION['username'])) {
    $username = $_COOKIE['username'];
    $username = $_SESSION['username'];
}

Now my problem is:

  1. Even when remember me is checked session is used and not cookies I tested it by exiting my browser. I can't figure out where code has gone wrong.
  2. In the second code if(isset($_COOKIE['username'])||isset($_SESSION['username'])) { is correct but I am not sure how to define username for both different situations also $username = $_COOKIE['username']; is giving me undefined index username. May be my way of setting cookies has gone wrong.
  • 写回答

1条回答 默认 最新

  • duanliang8464 2015-10-08 05:53
    关注

    Replace here

    if (isset($_POST['rememberme'])) {
    setcookie('username', $username,time()+31556926);
    }
    

    And in user functions

    if(isset($_SESSION['username']) {
          $username = $_SESSION['username'];
        }
     else if(isset($_COOKIE['username']){
          $username = $_COOKIE['username'];
        }
     else
        {
         //invalid ---
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?