login.php
<?php
// 使用PDO连接数据库
$pdo = new PDO("mysql:host=localhost;dbname=demo","root","rootroot");
// 判断do存在就执行里面的程序
if(isset($_POST['do'])){
$user = $_POST['user'];
$pass = md5($_POST['pass']);//..密码使用md5加密
// 准备SQL语句
$stmt = $pdo->prepare("select id,username from users where username=? and password=?");
// 执行SQL语句
$stmt->execute(array($user,$pass));
// 判断查到数据影响行数大于0就执行里面的程序(如果影响行数大于0,说明这个用户时存在的,就让登录)否则不让登录
if($stmt->rowCount()){
$result = $stmt->fetch(PDO::FETCH_NUM);//`fetch从结果集中获取下一行,返回一个索引以0开始的结果集列号的数组
list($id,$username) = $result;// list()函数用于在一次操作中给一组变量赋值
$time = time() + 24 * 60 *60;
setCookie("uid",$id,$time,"/");//..设置COOKIE
setCookie("username",$username,$time,"/");//..设置一个用户名COOKIE
setCookie("isLogin",1,$time,"/");//..设置一个登录判断的标记isLogin
echo '<script>location="usersearch.php"</script>';//..登录成功跳转到主页
echo "ok go";
}else{
echo "<script>alert('登录失败请重新登录)</script>";
}
}
// 处理退出登录的功能
if(isset($_GET['do']) && $_GET['do'] == 'logout'){
setCookie("uid",'',time() - 3600,"/");
setCookie("username",'',time() - 3600,"/");
setCookie("isLogin",'',time()-3600,"/");
echo '<script>alert("退出成功");location="login.php"</script>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<form action="login.php" method="post">
<table width="400" cellpadding="10" cellspacing="0" border="1">
<tr>
<td>账号:</td>
<td><input type="text" name="user"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="pass"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录" name="do"></td>
</tr>
</table>
</form>
</body>
</html>
cookie.php
<?php
// 判断是否是登录的,如果登录的,我们才可以通过 假如有这个变量$_COOKIE['isLogin'] = 1就是登录了
if(!(isset($_COOKIE['isLogin']) && $_COOKIE['isLogin'] == 1)){
echo '<script>
alert("你还没有登录,请登录!");
location = "login.php"
</script>';
}
echo "你好{$_COOKIE['pwd']}";
echo "你好{$_COOKIE['username']} | <a href='login.php?do=logout'>退出登录</a>";
?>
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
`password` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
INSERT INTO `users` VALUES ('1', 'admin', '21232f297a57a5a743894a0e4a801fc3');