Cookies PHP

我如何“内置”这个脚本的自动登录?

if (isset($_POST['login'])) {
$query = mysql_query("
          SELECT * FROM users 
          WHERE user_name = '".mysql_real_escape_string($_POST['username'])."' 
      AND user_password = '".mysql_real_escape_string($_POST['password'])."'
");

/* wrong login information? terminate the script */
if (!mysql_num_rows($query)){
header("Location: ./");
exit();
}

/* set session with unique index */
$_SESSION['id'] = mysql_result($query, 0, 'user_id');
mysql_query("UPDATE users SET user_online = '1' WHERE user_id = '{$_SESSION['id']}'");
header("Location: ./");
exit;
}

First, some suggestions:

  • You should store the passwords as salted hashes, not as plaintext.
  • You might want to change the way you do authentication in general. It might be a good idea to select the password (don't do "Select *" anyway) and compare it to the salted hash of the password the user typed in.
  • Now, you're asking, if I understand correctly, how to keep the user logged in. The basic idea is that you need to store a cookie with something that uniquely identifies the user (but make sure it is not something that be easily hijacked - so make it a really long string, like a SHA1 hash or something.) Set a far away expiration date on the cookie to keep the user logged in.

    Here is the function you use to set cookies in PHP.

    Then, when you load the page, you can check to see if that cookie exists. If the cookie exists, and the user does not have a SESSION variable, you can assign him one.


    //use request so you can link to the page and log the user in. it would be a good idead to use md5() on $_REQUEST['username'] and $_REQUEST['password'] so the password and usernames arent in plain text.  see http://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_md5
    
    if (isset($_REQUEST['login'])) {
    $query = mysql_query("
              SELECT * FROM users 
              WHERE user_name = '".md5($_REQUEST['username'])."' 
          AND user_password = '".md5($_REQUEST['password'])."'
    ");
    /* wrong login information? terminate the script */
    // there should only be one row returned with the query 
    if (mysql_num_rows($query)!=1){
    header("Location: ./");
    exit();
    }
    
    /* set session with unique index */
    $_SESSION['id'] = mysql_result($query, 0, 'user_id');
    mysql_query("UPDATE users SET user_online = '1' WHERE user_id = '{$_SESSION['id']}'");
    header("Location: ./");
    exit;
    }
    
    
    //now you can link to the page
    <a href="login.php?login=yes&username=**insert md5 hash of user name here**&password=md5 hash of password">auto login</a>
    
    链接地址: http://www.djcxy.com/p/21852.html

    上一篇: 如何访问虚拟主机网站的MySql数据库

    下一篇: Cookies PHP