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; }
首先,一些建议:
现在,如果我理解正确,请问如何让用户登录。基本思路是,您需要存储一个可以唯一标识用户的cookie(但要确保它不是轻易被劫持的东西 - 所以把它变成一个非常长的字符串,就像一个SHA1哈希或者其他东西一样。)在cookie上设置一个很远的到期日期以保持用户登录。
这里是你用来在PHP中设置cookie的功能。
然后,当你加载页面时,你可以检查cookie是否存在。 如果cookie存在,并且用户没有SESSION变量,则可以为其分配一个。
//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/21851.html
上一篇: Cookies PHP