Home > Backend Development > PHP Tutorial > Use php to implement simple background registration and login (with code)

Use php to implement simple background registration and login (with code)

不言
Release: 2023-04-03 11:24:02
Original
21867 people have browsed it

The content shared with you in this article is about using php to implement simple backend registration and login (with code). The content is of great reference value. I hope it can help friends in need.

I am a novice in PHP. I studied it some time ago, downloaded a background framework of PHP Chinese website, changed the style, and then added functional codes by referring to the projects formed on the Internet.

Another: I use the navicat for mysql sublime phpmystudy tool to achieve verification.

1. First create the layer and directory files

First put the hierarchical directory of the project:

If you only need to implement the registration and login function, many folders can be omitted. Because I also implemented the front-end code in it, I put the hierarchical directory of the entire system.

2. Entry file (index.php)

<?php 

/* PHP系统进入的入口页面*/
header("Content-type: text/html; charset=utf-8");
include(&#39;admin/login.html&#39;);//首页

?>
Copy after login

3. Login page

3.1 admin/ login.html (bootstrap framework and jquery are used here)

<!-- 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">

    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!-- <link rel="stylesheet" type="text/css" href="../public/css/base.css">  -->
    <link rel="stylesheet" type="text/css" href="css/b_login.css">
    <title></title>
</head>
<body>

<span class="visible-lg"><!-- bootstrap自适应工具  大屏幕>=1200px可见 必须全屏才可以使用-->
 <p class="login">
	<p class="loginmain">
		<h2>熊猫个人事务管理系统</h2>
			<form action="admin/login_check.php" class="form-horizontal" method="post">
		           <!-- 让表单在一行中显示form-horizontal -->

                <!-- 用户名 -->
		          <p class="form-group">
		          	<!-- for 属性规定 label 绑定到哪个表单元素 -->
		              <label for="username" class="col-lg-1 control-label">用户名</label>

		               <p class="col-lg-4">
		                <input type="text" name="username" id="username" class="form-control" placeholder="请输入登录账号"/>
		              </p>              
		          
		          </p>
				  <p class="form-group"></p>
				  <p class="form-group"></p>

                <!-- 密码 -->
		          <p class="form-group">
		              <label for="password" class="col-lg-1 control-label">密  码</label>
		              <p class="col-lg-4">
		                <input type="password" name="password" id="password" class="form-control" placeholder="请输入密码"/>
		              </p>              
		          </p>
                
                   <p class="form-group"></p>
                   <p class="form-group"></p>


                <!-- 验证码 -->
                <p class="form-group">
		              <!-- for 属性规定 label 与哪个表单元素绑定。 -->
		              <label for="captcha" class="col-lg-1 control-label">验证码</label>
		              
		             <p class="col-lg-2">
		              	<!-- ./ 当前路径 -->
                         <!-- 用户输入验证码的框  -->
		                <input type="text" name="captcha"  id="captcha" class="form-control" placeholder="请输入右图内容:"  />
                         <!--   当用户链接时,void(0) 计算为 0,但 Javascript 上没有任何效果。 -->
                     </p>
		             
		              <p>    

                          <!-- 验证码图片 -->
                          <a href="#" onclick="javascript:reflash()">
                       <img id="captcha_img" name="captcha_img"  alt="看不清楚,换一张"  border="1" src="admin/captcha.php?r=<?php echo rand(); ?>" width=100 height=30>  
                      </a>


                </p>
                  <p class="form-group"></p>
                  <p class="form-group"></p>


		          <p class="form-group">
		            <p class="col-lg-11 col-lg-offset-1">              
		                <span class="checkbox ">
		                    <label><input type="checkbox" name="" class="checkbox-inline">记住我</label> 
		                </span>           
		            </p>
		          </p>

               
		          <p class="form-group">
		          	<p>
		            <p class="col-lg-1 col-lg-offset-1">
		                <input type="submit" name="b_login" value="登录" class="btn btn-success btn-lg">
		            </p>

                    <p class="col-lg-1 col-lg-offset-1">
		            	<a href="admin/register.html">
		            		<input type="button" name="b_register" value="注册" class="btn btn-success btn-lg">
                        </a>
		            </p>
                       <p class="form-group"></p>
                       <p class="form-group"></p>
		            <span class="text" name="text"></span>  
		          </p>

		    </form>

	    </p>
	<p class="rightpic" >
		<p id="container" >
		</p>
	</p>
 </p>

		<p class="bottom">
	      版权所有 2017-2018 我是熊( ̄(工) ̄)工作室
       </p>
</span>
<script src="public/js/jquery-3.1.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="public/js/delaunay.js"></script>
<script src="public/js/TweenMax.js"></script>
<script src="js/effect.js"></script>

<script src="js/b_login.js"></script>
</body>
</html>
Copy after login

3.2 css/b_login.css (pictures can be based on personal preferences)

body{
	background-image: url(../picture/17.png);
	background-size: cover;
	font-size: 17px;
	font-family: "幼圆"
}
.login{
	width:1000px;
	height:500px;
	margin:100px auto;
	border:1px;
	background-color: rgba(0, 0, 0, 0.3);
	padding: 1px;
	position:relative;
	color:#fff;
}
.rightpic{
	width:500px;
	height:360px;
	position:absolute;
	right:30px;
	top:50px;
	opacity: 0.6;
}
.captcha{

	cursor:pointer
}
.text{
font-size: 18px;
margin-left: 180px;
text-align: center;
color: #f00;

}
.bottom{
	text-align: center;
	color: #fff;
}
#container{	
	position: relative;
	width:500px;
	height:330px;
}
canvas{ position: absolute;
 		backface-visibility: hidden; 
		-webkit-backface-visibility: hidden;
		-moz-backface-visibility: hidden;
	 	-ms-backface-visibility: hidden;
}
img {
	 position: absolute;
	 -webkit-transition: opacity .3s;
	  transition: opacity .3s;
}
Copy after login

3.3 js/b_login.js (verification code is involved here)

//alert($)
function reflash(){
	var change = document.getElementById(&#39;captcha_img&#39;);
	check.src="admin/captcha.php?r=<?php echo rand(); ?>";
}
$(document).ready(function(){//页面加载完成再加载脚本

   /*点击登录按钮后做的事件处理*/
	$(&#39;input[name="b_login"]&#39;).click(function(event){
		var $name = $(&#39;input[name="username"]&#39;);
		var $password = $(&#39;input[name="password"]&#39;); 
		var $captcha =  $(&#39;input[name="captcha"]&#39;); 
		var $text = $(".text");
		var _name = $.trim($name.val());//去掉字符串多余空格
		var _password = $.trim($password.val());
		var _captcha_img =  $.trim($captcha.val());
       
		if(_name==&#39;&#39;){
			$text.text(&#39;请输入用户名&#39;);
			$name.focus();
			return;
		}
		if(_password==&#39;&#39;){
			$text.text(&#39;请输入密码&#39;);
			$password.focus();
			return;
		}
		if(captcha==""){
	       $text.text(&#39;请输入验证码&#39;);
		   return;
		}


});

});
Copy after login

3.4 admin/captcha.php (I found this picture verification code from the Internet)

<?php

/*实现简单的验证码功能*/

//开启session
session_start();
//创建一个大小为 100*30 的验证码
$image = imagecreatetruecolor(100, 30);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);

$captch_code = &#39;&#39;;
for ($i = 0; $i < 4; $i++) {
    $fontsize = 6;
    $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $data = &#39;abcdefghijkmnpqrstuvwxy3456789&#39;;
    $fontcontent = substr($data, rand(0, strlen($data) - 1), 1);
    $captch_code .= $fontcontent;
    $x = ($i * 100 / 4) + rand(5, 10);
    $y = rand(5, 10);
    imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
}
//就生成的验证码保存到session
$_SESSION[&#39;authcode&#39;] = $captch_code;

//在图片上增加点干扰元素
for ($i = 0; $i < 200; $i++) {
    $pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));
    imagesetpixel($image, rand(1, 99), rand(1, 29), $pointcolor);
}

//在图片上增加线干扰元素
for ($i = 0; $i < 3; $i++) {
    $linecolor = imagecolorallocate($image, rand(80, 220), rand(80, 220), rand(80, 220));
    imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor);
}
//设置头
header(&#39;content-type:image/png&#39;);
imagepng($image);
imagedestroy($image);

?>
Copy after login

## 3.5 admin/login_check.php (This is the main function code. Before that It’s called panda_work. My username to connect to the database is root and the password is 123456)

<?php

	//开启Session
	session_start();
	header("Content-type:text/html;charset=utf-8");

	$link = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;123456&#39;,&#39;panda_work&#39;);

	if (!$link) {
	 die("连接失败:".mysqli_connect_error());
	}

	//接受提交过来的用户名及密码
	$username = @$_POST["username"];//用户名
	$password = @$_POST["password"];//密码
	$captcha = @$_POST["captcha"]; //验证码

	/*if($username == "")
	{
	 //echo "请填写用户名<br>";
	 echo"<script type=&#39;text/javascript&#39;>alert(&#39;请填写用户名&#39;);location=&#39;login.html&#39;; </script>";
	}

	if($password == "")
	{
	 //echo "请填写密码<br><a href=&#39;login.html&#39;>返回</a>"; 
	 echo"<script type=&#39;text/javascript&#39;>alert(&#39;请填写密码&#39;);location=&#39;login.html&#39;;</script>";
	}*/

	if($captcha != @$_SESSION[&#39;authcode&#39;]) //判断填写的验证码是否与验证码PHP文件生成的信息匹配
	{
	 echo "<script type=&#39;text/javascript&#39;>alert(&#39;验证码错误!&#39;);location=&#39;../index.php&#39;;</script>";
     return;
	}

	$sql = "select * from panda_admin";
	$result = mysqli_query($link, $sql);
	$rows = mysqli_fetch_array($result);

	if($rows) {
	 //拿着提交过来的用户名和密码去数据库查找,看是否存在此用户名以及其密码
		if ($username == $rows["name"] && $password == $rows["password"]) {

		$_SESSION[&#39;username&#39;] = $username;
		 //echo "验证成功!<br>";
		 echo "<script type=&#39;text/javascript&#39;>alert(&#39;登陆成功&#39;);location=&#39;../web/index.html&#39;;</script>";
		} else {
		 //echo "用户名或者密码错误<br>";
		 echo "<script type=&#39;text/javascript&#39;>alert(&#39;用户名或者密码错误&#39;);location=&#39;../index.php&#39;;</script>";
		 //echo "<a href=&#39;login.html&#39;>返回</a>";
		}
	}
?>
Copy after login

3.6 Database (just follow what you need)

3.7 Rendering

## 4. Registration page

4.1 admin/register.html (bootstrap framework and jquery are used here)

<!DOCTYPE html>
<html lang="en">
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./../bootstrap/css/bootstrap.min.css">
    <!-- <link rel="stylesheet" type="text/css" href="../public/css/base.css">  -->
    <link rel="stylesheet" type="text/css" href="../css/b_register.css">

    <title>后台注册页面</title>
</head>
<body>

<span class="visible-lg"><!-- bootstrap自适应工具  大屏幕>=1200px可见 必须全屏才可以使用 或者改百分比使用-->

<p class="register">

<form action="register_check.php" method="post" enctype="multipart/form-data">
  <p class="form-group">
    <label for="username">用户名</label>
    <input type="text" class="form-control" id="username" placeholder="Username" name="username">
  </p>

  <p class="form-group">
    <label for="nickname">昵称</label>
    <input type="text" class="form-control" id="nickname" placeholder="Nickname" name="nickname">
  </p>


  <p class="form-group">
    <label for="password">密码</label>
    <input type="password" class="form-control" id="password" placeholder="Password" name="password">
  </p>

 <p class="form-group">
    <label for="confirmPassword">确认密码</label>
    <input type="password" class="form-control" id="confirmPassword" placeholder="ConfirmPassword" name="confirmPassword">
  </p>
    
  <p class="form-group">
   
     <a href="#" onclick="javascript:reflash()">
      <img id="captcha_img" name="captcha_img"  alt="看不清楚,换一张"  border="1" src="captcha.php?r=<?php echo rand(); ?>" width=100 height=30>  
     </a>
      <p><p>
      <input type="text" class="form-control" id="captcha" placeholder="请输入上图验证码,按F5可刷新" name="captcha">
  </p>


  <p class="form-group">
    <label for="photoFile">头像</label>
    <input type="hidden" name="MAX_FILE_SIZE" value="10240000" id=""/>
    <input type="file" id="photoFile" name="photoFile">
  
  </p>

  <button type="submit" name="b_register" class="col-lg-1 col-lg-offset-3">提交</button>
  <p>
    <a href="../index.php">
     <button type="button" name="b_login" class="col-lg-1 col-lg-offset-3">返回</button>
    </a>
   <span class="text2"></span>
</form>

</p>

</span>
<p class="bottom">
    版权所有 2017-2018 我是熊( ̄(工) ̄)工作室
</p>

</body>
<script src="./../public/js/jquery-3.1.1.min.js"></script>
<script src="./../bootstrap/js/bootstrap.min.js"></script>
<script src="./../public/js/delaunay.js"></script>
<script src="./../public/js/TweenMax.js"></script>
<script src="../js/effect.js"></script>

<script src="../js/b_register.js"></script>
</html>
Copy after login

4.2 css/b_register.css (pictures can be based on personal preferences)

body{
	/*background-image: url(../picture/14.png);*/
	background-size: auto;
	font-size: 17px;
	font-family: "幼圆";
    background-image: url(../picture/19.jpg);
    background-repeat:no-repeat;
  /*  text-align: center;*/
    /*color: #00F;*/
}
.register{

	width:800px;
	height:600px;
	margin:200px auto;
	border:1px;
	background-color: rgba(0, 0, 0, 0.3);
	padding: 1px;
	position:relative;
	background-image: url(../picture/18.gif); 
    opacity: 0.8;
}

.bottom{
	text-align: center;
	color: #fff;
	margin-bottom: 100px;
}
Copy after login

4.3 js/b_register.js (image uploading is involved here)

//alert($)
function reflash(){
	var change = document.getElementById(&#39;captcha_img&#39;);
	check.src="admin/captcha.php?r=<?php echo rand(); ?>";
}
$(document).ready(function(){//页面加载完成再加载脚本

   /*点击登录按钮后做的事件处理*/
	$(&#39;input[name="b_register"]&#39;).click(function(event){
		var $name = $(&#39;input[name="username"]&#39;);
		var $password = $(&#39;input[name="password"]&#39;); 
		var $confirmPassword = $(&#39;input[name="confirmPassword"]&#39;);
		var $photoFile = $(&#39;input[name="photoFile"]&#39;);
		var $nickname = $(&#39;input[name="nickname"]&#39;);
		
		var $text2 = $(".text2");
        

		var _name = $.trim($name.val());//去掉字符串多余空格
		var _password = $.trim($password.val());
		var _confirmPassword = $.trim($confirmPassword.val());
		var _nickname = $.trim($.trim($nickname.val()));

		if(_name == &#39;&#39;){
			$text2.text(&#39;请输入用户名&#39;);
			$name.focus();
			return;
		}

		
		if(_nickname == ""){
            $text2.text(&#39;请输入昵称&#39;);
			$nickname.focus();
			return;
		}

		if(_password == &#39;&#39;){
			$text2.text(&#39;请输入密码&#39;);
			$password.focus();
			return;
		}

		if(_confirmPassword == ""){
           $text2.text("请输入验证码");
           $confirmPassword.focus();
           return;
		}

		if(_password !=_confirmPassword){
          $text2.text("两次输入的密码不一致");
          $password.focus();
          return;
		}
		if (_photoFile == "") {
			$text2.text("请选择一个图片文件");
			$photoFile.focus();
			return;
		}
		


});

});
Copy after login

4.4 admin/file_check.php (processing uploaded image files, this I also found it from the Internet, and changed a small part of the code,

# 也 You need to create a new storage file UPLOADS under the Admin folder)

r ##4.5 admin/register_check.php (it shares a data table with the login module)

<?php 
//1.处理文件信息
    $fileArr = @$_FILES["photoFile"];//input标签中的name
 
    //将文件信息保存在变量中
    $name = @$fileArr[&#39;name&#39;];//文件名
    $type = @$fileArr["type"];//文件类型
    $tmp_name = @$fileArr["tmp_name"];//文件临时存储位置的文件名
    $error = @$fileArr["error"];//文件的错误信息
    $size = @$fileArr["size"];//文件的大小
    
//2.新建存储文件的目录
    $filePath = "uploads"; 
    function createDir($filePath){
    	if(!file_exists($filePath)){ 
			$res = mkdir($filePath); 
			if($res){
				 echo "创建成功"; 
			}
		} 
	} 
	createDir($filePath);
	
	//因为要上传的文件为图片,所以此时设置允许的后缀名如下,如果其他文件则修改为txt等后缀 
	$allowExt=["image/png","image/jpeg","image/gif"];
	
//3.判断文件是否上传成功
    if($error===UPLOAD_ERR_OK){//UPLOAD_ERR_OK==0,上传成功
         if(!in_array($type,$allowExt)){//如果类型不在数组中
             exit("非法类型文件");

         }
         //判断后缀正确但不是图片的文件
         if(!getimagesize($tmp_name)){
             exit("不是真正的一张图片");
         }  
         
         $ext = pathinfo($name)["extension"];//获取文件后缀 
         $uniname = time().".".$ext;//生成一个唯一的文件名 
         $destination = $filePath."/".$uniname;
 
//4.move_uploaded_file将上传的文件移动到新位置。 若成功,则返回 true,否则返回 false
         $res = move_uploaded_file($tmp_name,$destination);
         
         if($res){//上传成功 
             //把图片服务器连接传出去:拼接出一个图片的src 
             $server = @$_SERVER["HTTP_ORIGIN"]; 
             $rootDir = pathinfo($_SERVER["REQUEST_URI"])["dirname"];  
             $imgPath = $server.$rootDir."/".$destination; //图片的src
            //echo "<img src=&#39;{$imgPath}&#39;>";//输出图片
            $_SESSION[&#39;imgPath&#39;] = $imgPath;
         }
         else{

             echo "<script type=&#39;text/javascript&#39;>alert(&#39;上传失败!&#39;);location=&#39;register.html&#39;;</script>";
         }
    }
    else{//上传失败,给出错误提示
         switch ($error) {
             case UPLOAD_ERR_INI_SIZE://1
                 die("上传的文件超过了PHP配置中upload_max_file大小的最大值");//die();结束程序
                 break;
             case UPLOAD_ERR_FORM_SIZE://2
                 die("上传的文件超过了HTML表单中隐藏域MAX_FILE_SIZE中value选项指定的值");
                 break;
             case UPLOAD_ERR_NO_TMP_DIR://6
                 die("没有找不到临时文件夹");
                 break;
             case UPLOAD_ERR_CANT_WRITE://7
                 die("文件写入失败");
                 break;
             case UPLOAD_ERR_EXTENSION://8 
                 die("php文件上传扩展没有打开");
                 break;
             case UPLOAD_ERR_PARTIAL://3 
                 die("文件只有部分被上传");
                 break;
             default:
                 break;
         }
    }
?>
Copy after login

4.6 Rendering (background image source from the Internet)

Finally

: After verification by myself, the two basic functions of registration and login can be achieved, and the interaction with the database is not a problem.

Related recommendations:

How PHP uploads pictures to the database for display code

php queue processing: PHP message queue implementation principle (Pictures and text)

The above is the detailed content of Use php to implement simple background registration and login (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template