您的位置:首页 > Web前端 > JQuery

后台使用php,前台使用html,css,jquery,javascript实现登录注册

2020-02-13 23:52 525 查看

简单介绍一下注册和登录功能的实现

注册

  • 注册的部分有注册用户名,秘密,确认密码,邮箱,电话号码,注册按钮和点击注册按钮完成注册.
  • 前端部分要做的事情就是用户输入的信息是否正确,格式是否符合
  • 当确定用户输入的信息正确后,客户端会将用户所输入的内容传给服务端.服务端得到的信息后会在进行一次判断信息的格式是否符合要求,无误后将德奥信息与数据库中的信息做对比,如有重复则会提示前端该用户名,手机号,邮箱等已经被注册,无重复的信息则将信息存入数据库并提示前端注册完成.

注册的页面布局Html代码如下

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<link rel="shortcut icon" href="../img/micon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<link rel="stylesheet" type="text/css" href="../css/regiter.css" />
<link rel="stylesheet" type="text/css" href="../css/lore.css" />
</head>

<body>
<div class="lore_box">
<div class="header">
<a href="#" class="logo">
</a>
</div>
<div class="from_box">
<form action="login.html" name="frm" οnsubmit='return checkAll()'>
<a href="#">注册Flyme账号</a>
<div><i>账号:</i><input type="text" placeholder="请输入账号" οnblur="checkUser(this)" name='username' />
<span>*&nbsp;账号中不能有数字,长度为4到16位</span></div><br/>

<div><i>密码:</i><input type="password" placeholder="请输入密码" οnblur="checkPass(this)" name='psd1' />
<span>*&nbsp;密码由数字字母下划线组成,长度6-16</span></div><br />

<div><i>确认密码:</i><input type="password" placeholder="确认密码" οnblur="checkPass2(this)" name='psd2' />
<span>*</span></div><br />

<div><i>邮箱:</i><input type="email" placeholder="请输入邮箱" οnblur="checkEma(this)" name='email' />
<span>*</span></div><br />

<div><i>手机号码:</i><input type="text" placeholder="请输入手机号" οnblur="checkPhone(this)" name='phone' />
<span>*</span></div><br />

<input type="submit" value="注册" id="sub" />
<p><a href="#">登录</a></p>
</form>
</div>
</div>
</body>
<script src="../js/utils.js"></script>
<script src="../js/cookie.js"></script>
<script src="../js/regiter.js"></script>
</html>

样式代码如下:

form {
position: absolute;
top: 10%;
right: 85px;
width: 510px;
height: 460px;
margin: 80px auto;
background: #fff;
padding: 30px 35px 0px 35px;
border-radius: 2px;
}

i {
display: inline-block;
font-style: normal;
width: 80px;
}

input {
width: 160px;
height: 30px;
}

span {
font-size: 14px;
color: #999;
}

a {
display: block;
font-size: 24px;
color: #387aff;
width: 200px;
margin: 20px auto;
}

#sub {
margin-left: 110px;
width: 80px;
height: 40px;
text-align: center;
line-height: 40px;
background-color: #387aff;
color: #fff;
}
body,html{
width: 100%;
height: 100%;
}
.lore_box {
width: 100%;
height: 100%;
}

.lore_box .header {
width: 100%;
height: 68px;
background: #fff;
}

.logo {
display: inline-block;
margin: 28px 140px;
width: 110px;
height: 20px;
background: url(https://uc-res.mzres.com/resources/uc/wlogin/base/images/base.png)-2px -4px no-repeat;
}

.lore_box .from_box {
width: 100%;
height: 90%;
background: url(https://uc-res.mzres.com/resources/uc/wlogin/member/images/banner.png)no-repeat;
background-size: cover;
}

.lore_box p a{
float: left;
margin: 20px 0;
margin-left: 8px;
font-size: 14px;
color: #387aff;
}
input{
padding-left: 10px;
border:0;
border: 1px solid silver;
border-radius: 2px;
}
input:focus{
border-color: blue;
}

js部分的逻辑代码如下:

let inputs = document.querySelectorAll('input');
let name, p1, p2, ema, phone1;

function mean(t, flag, info, intext) {
let va = t.value;
if(flag) {
t.nextElementSibling.innerHTML = '√'
t.nextElementSibling.style.color = 'green'
} else {
if(va == '') {
t.nextElementSibling.innerHTML = `*&nbsp;${info}不能为空`;
} else if(intext) {
t.nextElementSibling.innerHTML = intext;
}
t.nextElementSibling.style.color = 'red'

}

}

function checkUser(t) {
let reg = /^[^0-9]{4,16}$/;
let va = t.value;
if(reg.test(va)) {
name = true;
mean(t, name)
} else {
name = false;
let info = '账号';
mean(t, name, info)
}
}

function checkPass(t) {
let reg = /^\w{6,16}$/;
let va = t.value;
if(reg.test(va)) {
p1 = true;
mean(t, p1)
} else {
p1 = false;
let info = '密码';
mean(t, p1, info)
}
}

function checkPass2(t) {
let va = t.value;
let va1 = inputs[1].value;
if(va == va1 && va != '') {
p2 = true;
mean(t, p2)
} else {
p2 = false;
let intext = '*&nbsp;两次输入密码不一致'
let info = '确认密码';
mean(t, p2, info, intext)
}
}

function checkEma(t) {
let reg = /^\w+@(qq|163|sina)\.(com|cn)(.cn)?$/;
let va = t.value || '';
if(reg.test(va)) {
ema = true;
mean(t, ema)
} else {
ema = false;
let intext = '*&nbsp;邮箱格式错误'
let info = '邮箱';
mean(t, ema, info, intext)
}
}

function checkPhone(t) {
let reg = /^1[34578]\d{9}$/;
let va = t.value;
if(reg.test(va)) {
phone1 = true;
mean(t, phone1)
} else {
phone1 = false;
let intext = '*&nbsp;没有该手机号'
let info = '手机号';
mean(t, phone1, info, intext)
}
}

function checkAll() {
if(name && p1 && p2 && ema && phone1) {
regiterfn()
async function regiterfn(){
let p2=await pAjax({
url:'../server/regiter.php',
data:{
username:inputs[0].value,
psd:inputs[1].value
}
})
if(p2=='用户名已存在'){
inputs[0].nextElementSibling.innerHTML='用户名已存在'
inputs[0].nextElementSibling.style.color='red'
return false;
}else{
return true;
}
}

} else {
checkUser(inputs[0])
checkEma(inputs[3])
checkPass(inputs[1])
checkPass2(inputs[2])
checkPhone(inputs[4])
return false
}
}

后端使用php连接数据库的步骤

base.php(这个是基本的php连接数据库)

其他文件需要引用团队时候就导入就好了

<?php
header('content-type:text/html;charset=utf-8');
//连接mysql数据库
$conn=mysql_connect('localhost','root','root');
//连接指定数据库
mysql_select_db('meizu',$conn);

//设置数据库编码
mysql_query('set names utf8');
?>

resiger.php

<?php
/*
* @Date: 2019-11-13 20:26:51
* @LastEditTime: 2020-01-13 21:07:38
* @Author: 李芳芳
* @Github: https://github.com/J-Fan-Fan/
*/
//这个是导入php的方式
include 'base.php';
$name=$_GET['username'];
$psd=$_GET['psd'];
$sql="select * from `user` where name='$name';";
$sql2="insert into `user` (`name`,`pass`) VALUES('$name','$psd');";
$res=mysql_query($sql);
if(mysql_fetch_assoc($res)){
echo '用户名已存在';
}else {
$res2=mysql_query($sql2);
if(mysql_fetch_assoc($res2)){
echo '注册成功';
}

}

?>

登录功能的实现

登录页面最重要的三部分是用户名、密码与登入按钮 。用户分别输入用户名、密码后点击登录按钮进行登录操作。
前端部分要做的事主要是判断用户是否在以上两个部分输入了信息,接着判断输入信息的格式是否正确。
当用户内容输入正确后,客户端会将用户所输入的内容传给服务器。服务器得到信息后会再一次判断信息的格式等是否符合要求,无误后将得到的信息与数据库中的信息作比较。
如果在数据库中能找到用户名和密码与传入信息相同,则服务器设置cookie并返回HTTP状态码200给客户端,前端得到登录成功的信息就跳转到登录成功的页面;如果不同则返回HTTP状态码401给客户端,让客户端提示用户邮箱与密码不匹配、登录失败。
参照于链接:https://www.jianshu.com/p/a4dcf364fe81

html页面布局的代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="shortcut icon" href="../img/micon.ico" type="image/x-icon">
<link rel="stylesheet" type="text/css" href="../css/main.css"/>
<link rel="stylesheet" type="text/css" href="../css/login.css"/>
<link rel="stylesheet" type="text/css" href="../css/lore.css"/>
<script src="../js/jquery.js"></script>

</head>
<body>
<div id="cover"></div>
<div class="lore_box">
<div class="header">
<a href="#" class="logo">
</a>
</div>
<div class="from_box">
<form action="###" name="frm" method="post">
<h2>登录</h2>
<input type="text" placeholder="请输入账号" name='username' />
<br/>
<input type="password" placeholder="请输入密码" name='password' />
<br />
<input type="submit" value="登录" class="sub"/>
<p><a href="regiter.html">注册</a></p><p class="p2"><a href="#">忘记密码?</a></p>
<div id='hint_box'>
<div class="hint">
<h3>登录失败</h3>
<p id='tishi'></p>
</div>
<h3 id="sure">确定</h3>
</div>
</form>
</div>
</div>
</body>
<script src="../js/utils.js"></script>
<script src="../js/cookie.js"></script>
<script src="../js/login.js"></script>
</html>

css样式布局如下:

login.css
form {
width: 298px;
position: absolute;
top: 24%;
right: 185px;
background-color: #FFF;
padding: 30px 35px 0px 35px;
border-radius: 2px;
}

input {
width: 290px;
height: 48px;
margin-top: 20px;
}

.sub {
cursor: pointer;
color: #fff;
height: 46px;
font-size: 14px;
line-height: 46px;
text-align: center;
width: 302px;
background-color: #387aff;
}

.lore_box form h2 {
width: 50px;
margin: 20px auto;
}

.lore_box .p2 {
margin-left: 190px;
}
#hint_box{
z-index:66;
color: #353536;
padding-top: 30px;
text-align: center;
position: absolute;
left: 34px;
top: 52px;
width:304px;
height: 160px;
border-radius: 6px;
background-color:#fff;
display: none;
}
.hint{
width: 100%;
height: 110px;
border-bottom: 1px solid #F4F4F4;
}
.hint p{
margin-top: 16px;
}
#hint_box h3{
line-height: 38px;
font-weight: normal;
}
#hint_box #sure {
line-height: 46px;
cursor: pointer;
}
#cover{
display: none;
position: fixed;
left: 0;
top:0;
z-index: 6;
width: 100%;
height: 100%;
background: rgba(126,126,126,0.5);
}

实现登录的逻辑js代码如下:

login.js
let src1 = window.location
console.log(src1);
//?path1=%22car.html?id=4%22
let reg = /^\?path1=%22(.+)%22$/;
$('form').submit(function(e) {
//阻止默认提交事件
var e = e || window.event
e.preventDefault()
//获取输入框中的用户名和密码
let user = $('input:eq(0)').val()
let pass = $('input:eq(1)').val()
//调用和数据库里面的用户名和密码,将用户名和密码放入 到数据库里面查看是否已经存在这样子的密码和用户名
loginfn()
async function loginfn() {
let p = await pAjax({
url: '../server/login.php',
data: {
user1: user,
pass1: pass
}
})
//如果存在的话
if (p == 'ok') {
console.log('ok')
//就设置cookie有效的时间
setCookie('login', 11, 60 * 60 * 24 * 10)
if (reg.test(src1.search)) {
//				0: "?path1=%22goodsdetail.html%22"
//				1: "goodsdetail.html"
let regres = reg.exec(src1.search)
window.location.href = regres[1]
} else {
window.location.href = 'phonelist.html'
}
} else {
let name = $(':text').val()
let psd = $(':password').val()
if (name == "" || psd == "") {
$('#tishi').text('账号和密码不能为空')
} else {
$('#tishi').text('账号或密码错误,请重新输入')
console.log('error')
}
$('#cover').css('display', 'block')
$('#hint_box').css('display', 'block')

}
}

})
$('#sure').on('click', function() {
$('#cover').css('display', 'none')
$('#hint_box').css('display', 'none')
})

后台代码php实现登录如下:

login.php

<?php
include 'base.php';
$name=$_GET['username'];
$psd=$_GET['psd'];
$sql="select * from `user` where name='$name';";
$sql2="insert into `user` (`name`,`pass`) VALUES('$name','$psd');";
$res=mysql_query($sql);
if(mysql_fetch_assoc($res)){
echo '用户名已存在';
}else {
$res2=mysql_query($sql2);
if(mysql_fetch_assoc($res2)){
echo '注册成功';
}

}

?>

公用的工具类代码

utils.js

function ajax(options) {
// 1. 判断用户有没有传递 url
if (!options.url) {
// 告诉使用者 url 必须传递
// 手动抛出一个错误
// throw 手动抛出异常
throw new Error('url 是必填项')
}

// 2. 准备一套默认值
const defInfo = {
data: '',
dataType: 'string', // 不需要执行 JSON.parse
async: true,
type: 'GET',
success: function () {}
}

// 3. 把用户的信息替换到默认值里面
for (let attr in options) {
defInfo[attr] = options[attr]
}

// 4. 检测所有的参数是不是符合规则
// 4-1. 检测 async
if (typeof defInfo.async !== 'boolean') {
// async 参数不和规则
throw new Error('async 只接受布尔值')
}

// 4-2. 检测 type
if (!(defInfo.type.toUpperCase() === 'GET' || defInfo.type.toUpperCase() === 'POST')) {
// type 是一个 GET 或者 POST 以外的东西
throw new Error('目前只接受 get 和 post请求,请期待更新')
}

// 4-3. 检测 success
if (typeof defInfo.success !== 'function') {
throw new Error('success 必须是一个函数')
}

// 4-4. 检测data
//      key=value&key=value
//      {}
if (!(typeof defInfo.data === 'string' && /^(\w+=\w+&?)*$/.test(defInfo.data) || Object.prototype.toString.call(defInfo.data) === '[object Object]')) {
// 证明是一个不合法字符串或者不是个对象
throw new Error('data 只能传递 key=value&key=value 的字符串或者 对象')
}

// 5. 搞定参数 data
let str = ''
if (Object.prototype.toString.call(defInfo.data) === '[object Object]') {
// 循环遍历对象
for (let attr in defInfo.data) {
str += `${attr}=${defInfo.data[attr]}&`
}

// slice 截取字符串 从哪个索引开始 到哪个索引
// 传递一个负整数的时候就等于 length + 负整数
defInfo.data = str.slice(0, -1)
}

// 6. 开始发送 ajax 请求
// try {} catch (e) {}
// 6-1. 创建 ajax 对象
let xhr
try {
// 如果由这个方法,catch 不执行
xhr = new XMLHttpRequest()
} catch (err) {
// 如果上面出错了,那么就执行我这个东西
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}

// 6-2. 配置请求地址和请求参数
//      判断是不是 get 请求,如果是,拼参数
xhr.open(defInfo.type, defInfo.url + (defInfo.type.toUpperCase() === 'GET' ? '?' + defInfo.data : '') + (defInfo.type.toUpperCase() === 'GET' ? '&_=' + new Date().getTime() : ''), defInfo.async)

// 6-3. 发送请求
// 单独判断一下是不是 post 请求
if (defInfo.type.toUpperCase() === 'POST') {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send(defInfo.data)
} else {
xhr.send()
}

// 6-4. 接受响应
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && /2\d{2}/.test(xhr.status)) {
// 判断 dataType 是不是 json
if (defInfo.dataType === 'json') {
defInfo.success(JSON.parse(xhr.responseText))
} else {
defInfo.success(xhr.responseText)
}
}
}
}

function pAjax(options) {
return new Promise(function (resolve, reject) {
ajax({
url: options.url,
data: options.data || '',
dataType: options.dataType || '',
async: options.async || true,
type: options.type || 'GET',
success (res) {
resolve(res)
}
})
})
}

设置cookie的js逻辑代码如下

/**
* setCookie 用来设置 cookie 的方法
* @param {STRING} key 你要存储的 cookie 的名称
* @param {STRING} value 你要存储的 cookie 的值
* @param {INT} expires 你设置的过期时间,按照秒计算的
*/
function setCookie(key, value, expires) {
var time = new Date()
var t1 = time.getTime() - 1000 * 60 * 60 * 8 + 1000 * expires
time.setTime(t1)

document.cookie = `${key}=${value};expires=${expires ? time : ''}`
}

/**
* getCookie 用域获取 cookie 的某一个属性的值
* @param {STRING} key 你要获取的 cookie 属性的名
* @return {STRING}  就是你要获取的 cookie 属性的值
*/
function getCookie (key) {
var arr = document.cookie.split('; ')

// 提前准备一个变量,用于记录 cookie 的值
var value = ''

// 如果数组中的 第 0 项 为 true
if (arr[0]) {
// 如果能进入到这里,证明 arr[0] 为 true
// console.log(arr)

// 遍历数组
arr.forEach(item => {
var tmp = item.split('=')

if (tmp[0] === key) {
value = tmp[1]
}
})
}

return value
}

/**
* delCookie 用来删除 cookie 中指定的内容的
* @param {STRing} key 你要删除的 cookie 的名
*/
function delCookie (key) {
setCookie(key, 'suibain', -10)
}

Cookie

次部分转载于:链接:https://www.jianshu.com/p/a4dcf364fe81
  前面我有提到cookie这个东西,Cookie主要是指某些网站为了辨别用户的身份而存储在用户本地终端上的数据。那接下来我就简单介绍一下cookie是什么、有什么特点。

1.Cookie是什么?

cookie是客户端访问服务器后,服务器传给客户端的一段数据。
客户端需要保存这段数据,不得轻易删除。
以后每次客户端访问该服务器都必须带上这段数据。

1.Cookie有什么特点?

服务端通过Set-Cookie响应头设置Cookie。
客户端得到Cookie之后,每次访问相同域名的网页时都要带上这个Cookie。
服务器读取Cookie就知道了用户的登录信息。
客户端要在一段时间内保存这个Cookie,
Cookie默认在用户关闭页面后失效,但是后端代码可以任意设置过期时间。
Cookie的存储大小为4K。
  以上我简单介绍了一下Cookie,想要了解更多的Cookie知识可以去MDN查询了解。Cookie有一个很大的缺点那就是稍微有点前端知识就可以随意串改Cookie,这样会导致有人恶意入侵获取所有用户隐私信息,为了防止这种情况出现配合session来加强Cookie的安全性,具体如何实现各位可以百度一下(or google)。

至此网页注册与登录两个部分的过程代码解析就结束了,看到这里你对网页注册和登录功能是如何实现的会有一个大概的了解,但是这么多代码可能看起来就会害怕(哈哈哈,我也是),如果愿意你可以有空自己写一个demo实现一下,这样会加深理解!

  • 点赞 2
  • 收藏
  • 分享
  • 文章举报
l元芳怎么看 发布了48 篇原创文章 · 获赞 18 · 访问量 4639 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: