PHP注册、登录、退出实战小案例
程序员文章站
2022-03-03 21:37:07
...
PHP注册、登录、退出实战小案例
效果图
(开发环境:Windows,wampserver)
- 首先,创建数据库userinfo,添加数据表user,如下
- 创建项目结构,并引入公共资源
- config/ 文件夹下面创建
database.php
文件,代码如下:
<?php
return [
'type' => $type ?? 'mysql',
'username' => $username ?? 'root',
'password' => $password ?? '',
'host' => $host ?? 'localhost',
'port' => $port ?? '3306',
'charset' => $charset ?? 'utf8',
'dbname' => 'userinfo'
];
- 编写
login.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录-恋爱ya</title>
<link rel="stylesheet" href="/public/static/css/adminlte.min.css">
<style>
* {
padding: 0;
margin: 0;
}
.container_header {
width: 100%;
height: auto;
position: relative;
}
.container_header div img {
width: 100%;
height: auto;
}
.container_header .container_form {
position: absolute;
top: 65%;
left: 15%;
height: 200px;
width: 70%;
/* border: 1px solid red; */
}
.container_form input {
width: 100%;
height: 2.5em;
border: none;
border-bottom: 1px solid #d0d0d0;
}
.container_form label {
font-size: 1em;
font-weight: normal;
color: lightslategray;
}
::placeholder {
color: #d0d0d0;
}
.container_form .click_button button {
width: 100%;
font-size: 1.4em;
height: 1.5em;
color: #fff;
font-weight: 500;
position: absolute;
background-color: #ffdf58;
border: none;
border-radius: 20px;
margin-top: 10px;
}
.container_form a {
color: #fb948b;
font-size: 0.8em;
position: absolute;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container_header">
<div class="container_img">
<img src="./public/static/img/bgimg.jpg" alt="">
</div>
<div class="container_form">
<form action="" role="form" id="sub_form">
<div class="input_uname form-group">
<label for="uname">用户名:</label>
<input type="text" id="uname" name="uname" placeholder="请输入用户名" autofocus>
</div>
<div class="input_upwd form-group">
<label for="upwd">密 码:</label>
<input type="password" id="upwd" name="upwd" placeholder="请输入密码">
</div>
<div class="click_button">
<button type="submit" class="">登 录</button>
</div>
<a href="reg.php">没有账号?点击注册呀~</a>
</form>
</div>
</div>
<script src="/public/static/js/jquery.min.js"></script>
<script src="/public/static/js/jquery.form.min.js"></script>
<script src="/public/static/js/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
$.validator.setDefaults({
submitHandler: function(form) {
$('#sub_form').ajaxSubmit({
url: 'dosubmit.php?type=login',
dataType: 'json',
type: 'POST',
success: function(res) {
if (res.status == 1) {
alert('登录成功');
window.location.href = "index.php";
} else {
alert('用户名或密码错误,请检查');
}
},
error: function() {
alert('系统出错啦,请稍后重试ya');
}
})
}
});
// 对表单的校验
$('#sub_form').validate({
rules: {
uname: {
required: true,
rangelength: [2, 10]
},
upwd: {
required: true,
minlength: 6
}
},
messages: {
uname: {
required: "账户不能为空",
rangelength: '用户名必须2-10字符'
},
upwd: {
required: "密码不能为空",
minlength: "密码至少6位"
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
});
</script>
</body>
</html>
- 编写
reg.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注册-恋爱ya</title>
<link rel="stylesheet" href="/public/static/css/adminlte.min.css">
<style>
* {
padding: 0;
margin: 0;
}
.container_header {
width: 100%;
height: auto;
position: relative;
}
.container_header div img {
width: 100%;
height: auto;
}
.container_header .container_form {
position: absolute;
top: 60%;
left: 15%;
height: 200px;
width: 70%;
/* border: 1px solid red; */
}
.container_form input {
width: 100%;
height: 2.5em;
border: none;
border-bottom: 1px solid #d0d0d0;
}
.container_form label {
font-size: 1em;
font-weight: normal;
color: lightslategray;
}
::placeholder {
color: #d0d0d0;
}
.container_form .click_button button {
width: 100%;
font-size: 1.4em;
height: 1.5em;
color: #fff;
font-weight: 500;
position: absolute;
background-color: #ffdf58;
border: none;
border-radius: 20px;
margin-top: 10px;
}
.container_form a {
color: #fb948b;
font-size: 0.8em;
position: absolute;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="container_header">
<div class="container_img">
<img src="./public/static/img/bgimg.jpg" alt="">
</div>
<div class="container_form">
<form action="" role="form" id="sub_form">
<div class="input_uname form-group">
<label for="uname">用户名:</label>
<input type="text" id="uname" name="uname" placeholder="请输入用户名" autofocus>
</div>
<div class="input_upwd form-group">
<label for="upwd">密 码:</label>
<input type="password" id="upwd" name="upwd" placeholder="请输入密码">
</div>
<div class="input_upwd form-group">
<label for="upwd_check">确认密码:</label>
<input type="password" id="upwd_check" name="upwd_check" placeholder="请再次输入密码">
</div>
<div class="click_button">
<button type="submit" class="">注 册</button>
</div>
<a href="login.php">已有账号,前往登录ya~</a>
</form>
</div>
</div>
<script src="/public/static/js/jquery.min.js"></script>
<script src="/public/static/js/jquery.form.min.js"></script>
<script src="/public/static/js/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
$.validator.setDefaults({
submitHandler: function(form) {
$('#sub_form').ajaxSubmit({
url: 'dosubmit.php?type=reg',
dataType: 'json',
type: 'POST',
success: function(res) {
if (res.status == 1) {
alert('注册成功');
window.location.href = "index.php";
} else {
alert('注册失败,可能是系统出错了~');
}
},
error: function() {
alert('系统出错啦,请稍后重试ya');
}
})
}
});
// 对表单的校验
$('#sub_form').validate({
rules: {
uname: {
required: true,
rangelength: [2, 10]
},
upwd: {
required: true,
minlength: 6
},
upwd_check: {
equalTo: "#upwd",
required: true,
minlength: 6
}
},
messages: {
uname: {
required: "账户不能为空",
rangelength: '用户名必须2-10字符'
},
upwd: {
required: "密码不能为空",
minlength: "密码至少6位"
},
upwd_check: {
equalTo: "两次密码输入值需一致",
required: "请再次确认密码",
minlength: "密码至少6个字符"
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
});
</script>
</body>
</html>
- 编写
common.php
,进行用户登录注册检验
<?php
session_start();
// 这个相当于模型文件 model
//连接数据库
require 'connect.php';
//用户登录检测
function loginCheck($name, $pwd)
{
$sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? ";
// prepare准备阶段
global $pdo;
$stmt = $pdo->prepare($sql);
$res = $stmt->execute([$name, md5($pwd)]);
if ($res) {
$res = $stmt->fetch(PDO::FETCH_ASSOC);
// 验证通过
if ($res) {
// 开启session 将用户的信息储存在服务器上的某个文件中
$_SESSION['username'] = $res['username'];
return true;
} else {
return false;
}
}
}
//用户注册
function insertData($name, $pwd, $gender, $created_at)
{
$flag = false;
global $pdo;
$pwd = md5($pwd);
$sql = "INSERT INTO `user` SET `username` =?,`password`=?, `gender`=?,`created_at`=? ";
$stmt = $pdo->prepare($sql);
$stmt->execute([$name, $pwd, $gender, $created_at]);
if ($stmt->rowCount() == 1) {
// 插入数据成功
$flag = true;
}
return $flag;
}
- 编写
dosubmit.php
,处理前端传过来的数据
<?php
// 控制器文件
require 'common.php';
// 后端可接受前端传过来的参数
$name = isset($_POST['uname']) ? $_POST['uname'] : null;
$pwd = isset($_POST['upwd']) ? $_POST['upwd'] : null;
$gender = isset($_POST['gender']) ? $_POST['gender'] : null;
$created_at = time();
$type = strtolower($_GET['type']);
// 请求分发器 注册 登录 退出登录
switch ($type) {
case 'login':
$res = loginCheck($name, $pwd);
if ($res) {
echo json_encode(['status' => 1, 'msg' => '登录成功了'], 320);
exit;
}
echo json_encode(['status' => 0, 'msg' => '用户名或密码错误'], 320);
break;
case 'reg':
// 新增数据;
$res = insertData($name, $pwd, $gender, $created_at);
if ($res) {
echo json_encode(['status' => 1, 'msg' => '注册成功'], 320);
exit;
}
echo json_encode(['status' => 0, 'msg' => '注册失败'], 320);
break;
case 'logout':
// 删除注册的session数据的文件 关闭session会话
// unset($_SESSION);
session_destroy();
header('Location:index.php');
break;
default:
exit('非法请求');
}
- 编写
index.php
,完成登录跳转
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>恋爱呀~</title>
<style>
* {
margin: 0;
padding: 0;
list-style: 0;
text-decoration: none;
box-sizing: border-box;
}
header {
display: flex;
background-color: #ffce00;
padding: 0.5em 1em;
opacity: 0.5;
}
a {
color: #fff;
text-decoration: none;
}
a:hover,
span {
color: white;
}
header nav {
margin-left: auto;
}
</style>
</head>
<body>
<header>
<a href="">首页</a>
<nav>
<!-- 如果没有session信息 代表未登录 显示登录 注册按钮-->
<?php if (!isset($_SESSION['username']) || empty($_SESSION['username'])) : ?>
<a href="login.php">登录</a>
<a href="reg.php">注册</a>
<?php else : ?>
<a href="javascript:;">欢迎<b><?= $_SESSION['username'] ?></b>小可爱呀~</a> 
<a href="dosubmit.php?type=logout" id="logOut">退出</a>
<?php endif ?>
</nav>
</header>
</body>
</html>