如果大家经常上网或许见到登陆框之类的,比如网易邮箱登陆时有个“记住用户名”选项,也就是当第一次登录时如果选中了“记住用户名”选项并能顺利登录,那么当第二次登陆时输入用户名后密码框中就自动输入密码(虽然这样做有些不安全),但类似的还有CSDN首页登录时有个“两周内不再登录”选项,其实两者的原理都是一样的,都是利用cookie来实现的。
那么究竟是怎么实现的呢?下面给出一个简单的例子来参考:
客户端代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Cookies Example</title>
<script type="text/javascript">
function getCookie(sName) {
var sRE = "(?:; )?" + sName + "=([^;]*);?";
var oRE = new RegExp(sRE);
if (oRE.test(document.cookie)) {
return decodeURIComponent(RegExp["$1"]);
} else {
return null;
}
}
//onload事件处理函数用来查找是否有包含用户信息的cookie,
//如果找到了就将信息填入表单中
window.onload = function () {
var sName = getCookie("personName");
var sEmail = getCookie("personEmail");
if (sName && sEmail) {
var oForm = document.forms["feedbackForm"];
oForm.personName.value = sName;
oForm.personEmail.value = sEmail;
}
};
</script>
</head>
<body>
<p>This is a sample feedback form using cookies. This example requires
you to use PHP for server-side processing.</p>
<form name="feedbackForm" method="post" action="submitfeedback.php">
<p>Name: <input type="text" name="personName" /><br />
E-mail Address: <input type="text" name="personEmail" /><br />
Feedback:<br /> <textarea rows="10" cols="50" name="feedbackText"></textarea><br />
<input type="checkbox" name="rememberMe" value="yes" /> Remember Me<br />
<input type="submit" value="Submit Feedback" />
</form>
</body>
</html>
服务器端代码:
<?php
if ($rememberMe == "yes") {
setcookie("personName", $personName, time() + 1000 * 60 * 60 * 24 * 365);//设置cookie当前时间一年后失效,下同
setcookie("personEmail", $personEmail, time() + 1000* 60 * 60 * 24 * 365);
}
?>
<html>
<head>
<title>Cookies Example</title>
</head>
<body>
<p>Thank you for submitting feedback!</p>
</body>
</html>
运行一下看看效果也许你会明白其中的原理