登录前验证用户动态切换头像
效果图1
效果图2
效果图3
效果图4
登录页面由JS调用AJAX请求服务器
示例代码
<!--
提交数据表单
验证用户账号密码
连接数据库
-->
<?php
//保存用户信息
session_start();
//载入配置文件
require_once '../config.php';
//1.效验
function login(){
//效验用户名
if (empty($_POST['email'])) {
$GLOBALS['message'] = "用户名为空";
return;
}
if (empty($_POST['password'])){
$GLOBALS['message'] = "密码为空";
return;
}
// //提供假数据
// $email = $_POST['email'];
// $password = $_POST['password'];
// if ($email !== 'admin' ){
// $GLOBALS['message'] ="用户名不存在";
// return;
// }
// if ($password !== '1234'){
// $GLOBALS['message'] = "密码不正确";
// return;
// }
//保存用户信息
$email = $_POST['email'];
$password = $_POST['password'];
//2.持久化
//数据库连接
$conn = mysqli_connect(BXiu_DB_HOST, Bxiu_DB_USER, BXiu_DB_PASS, BXiu_DB_NAME);
if (!$conn){
exit("<h1>数据库登录失败</h1>");
}
//数据库查询
$query = mysqli_query($conn,"select * from users where email ='{
$email}' limit 1");
//判断是否登录成功
if (!$query){
$GLOBALS['message'] = "登录失败";
return;
}
//遍历
$user = mysqli_fetch_assoc($query);
//记录session 这时候,当前用户登录的信息已经保存在SESSION中
$_SESSION['current_login_user'] = $user;
if(!$user){
$GLOBALS['message'] = "用户不存在";
return;
}
//数据库密码验证
if($user['password'] !==$password ){
$GLOBALS['message'] = "用户密码不正确";
return;
}
//3.响应
header('Location:/admin/index.php');
}
if (empty($_SERVER['REQUEST_METHOD'] ==='$_POST')){
login();
}
?>
<!DOCTYPE php>
<php lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Sign in « Admin</title>
<link rel="stylesheet" href="../assets/vendors/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<link rel="stylesheet" href="../assets/vendors/animate/animate.css" >
</head>
<body>
<div class="login">
<!--清除表单的自动效验功能 novalidate-->
<!--客户端的自动完成功能 autocomplete-->
<form class="login-wrap<?php echo isset($message) ? " shake animated" : "" ;?>" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" autocomplete="off" novalidate>
<img class="avatar" src="../assets/img/default.png">
<!-- 有错误信息时展示 -->
<!-- <div class="alert alert-danger">
<strong>错误!</strong> 用户名或密码错误!
</div> -->
<!--提示错误信息-->
<?php if(isset($message)):?>
<div class="alert alert-danger">
<strong>错误!</strong><?php echo $message;?>
</div>
<?php endif?>
<div class="form-group" >
<label for="email" class="sr-only">邮箱</label>
<input id="email" name="email" type="email" class="form-control" placeholder="邮箱" autofocus >
</div>
<div class="form-group">
<label for