doushenmao9036 2011-03-27 01:03
浏览 34
已采纳

php用户自动登录

Can't find answer to my question. I'm creating registration and need autologin for user with cookie. What kind of information should be stored in cookie? Is it username + hash password or what

  • 写回答

3条回答 默认 最新

  • dousha1394 2011-03-27 04:35
    关注

    First, just to echo what everyone else has said, this isn't so much an auto-login feature as it is a 'remember me if I navigate away from the page' feature.

    How I have seen it done in the past is similar to the implementation explained by frostymarvelous. Basically I have seen 3 cookies used:

    Cookie 1:

    • name - 'username'
    • value - user's name

    Cookie 2:

    • name - 'salt'
    • value - random salt created for this particular login

    Cookie 3:

    • name - 'authentication_hash'
    • value - Hash of a couple unique pieces of data that only your website can duplicate. If you can duplicate this value in the cookie, then make sure the user doesn't have to login again.

    Basically, cookie 3 is the most important cookie and I would include a couple things in this to prevent it from being duplicated easily:

    <?php 
    function isAuthenticationCookieValid() {
        // $websitePassword would be a unique string stored in a file that is only
        // accessible by the server running your website. 
        include("websitePassword.php");
    
        // $hashOfUserPassword should be a hash of the user's password and should be
        // retrieved from the database in hashed form because that is how you should
        // store passwords.
        $hashOfUserPassword = retrieveUserPasswordFromDatabase($_COOKIE['username']);
    
        // $salt should just be read from cookie.
        $salt = $_COOKIE['salt'];
    
        $authenticationValue = sha1($websitePassword . $salt . $hashOfUserPassword);
    
        // Compare authentication value in cookie with calculated authentication value.
        return $authenticationValue == $_COOKIE['authentication_hash'];
    }
    ?>
    

    The contents of 'websitePassword.php' should just be:

    <?php
        $websitePassword = "secretWebsitePassword";  // Obviously use a better password
    ?>
    

    I would also suggest making the cookies expire after a timelimit to make your website more secure and you could possibly add a time element to your hash so if they try to use that particular hash after a particular amount of time, they will not be logged in automatically.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题