1.创建一个login.php文件,包含表单及表单登录验证动作
<?php
error_reporting(E_ALL & ~E_NOTICE);
function clearcookie(){
setcookie('username','',time()-3600);
setcookie('password','',time()-3600);
setcookie('isLogin','',time()-3600);
}
if($_GET['action']=='login'){
clearcookie();
if(($_POST['username']=='liuren')&&($_POST['password']=='158369')){
setCookie('username','liuren',time()+3600);
setCookie('password','158369',time()+3600);
setCookie('isLogin',1,time()+3600);
header('location:index.php');
}else{
die("用户名或密码不正确!");
}
}elseif($_GET['action']=='logout'){
clearcookie();
}
?>
<html>
<title>登录界面</title>
<h2>用户登录</h2>
<body>
<form action=login.php?action=login method='post'>
用户名:<input type='text' name='username' value=''><br>
密 码:<input type='password' name='password' value=''><br>
<input type='submit' name='submit' value='登录'>
</form>
</body>
</html>
2.创建网站主页面文件index.php
<?php
if(!((isset($_COOKIE['isLogin']))&&($_COOKIE['isLogin']==1))){
header("location:login.php");
exit;
}
?>
<html>
<title>网站主页面</title>
<h2>主页内容</h2>
<body>
<?php
echo "您好,".$_COOKIE['username']."欢迎登录主页面!";
?>
<a href='login.php?action=logout'>退出登录</a>
<p>这是网站主页内容</p>
</body>
</html>