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条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图