Home  >  Article  >  Backend Development  >  Implementing user registration and login function based on PHP

Implementing user registration and login function based on PHP

高洛峰
高洛峰Original
2016-12-20 09:17:251991browse

This article introduces the realization of user registration and login function based on PHP. This project is divided into four parts: 1. Front-end page production, 2. Verification code production, 3. Implementation of registration and login, 4. Functional improvement. Details can be found below.

Verification code production

1. Experiment introduction

This experiment will lead you to use object-oriented thinking to encapsulate a verification code class. And displayed on the registration and login interface. Through the study of this experiment, you will understand the OOP ideas of PHP, as well as the use of GD library and verification code generation.

1.1 Knowledge points involved

PHP

GD library

OOP programming

1.2 Development tools

sublime, a convenient and fast text editor. Click on the lower left corner of the desktop: Application menu/Development/sublime

2. Encapsulation verification code class

2.1 Create a directory and prepare fonts

Create an admin directory in the web directory as our backend directory to store the backend code document. Create a fonts directory under admin to store the fonts required for making verification codes.

Create a new Captcha.php file under admin. This is the verification code file we need to edit.结 The current directory hierarchical structure:

Edit Captcha.php file: Implementing user registration and login function based on PHP

<?php
/**
* Captcha class
*/
class Captcha
{
   
  function __construct()
  {
    # code...
  }
}

Add this type of private attributes and structural methods:

<?php
/**
* Captcha class
*/
class Captcha
{
  private $codeNum;  //验证码位数
  private $width;  //验证码图片宽度
  private $height;  //验证码图片高度
  private $img;  //图像资源句柄
  private $lineFlag;  //是否生成干扰线条
  private $piexFlag;  //是否生成干扰点
  private $fontSize;  //字体大小
  private $code;  //验证码字符
  private $string;  //生成验证码的字符集
  private $font;  //字体
  function __construct($codeNum = 4,$height = 50,$width = 150,$fontSize = 20,$lineFlag = true,$piexFlag = true)
  {
    $this->string = &#39;qwertyupmkjnhbgvfcdsxa123456789&#39;;  //去除一些相近的字符
    $this->codeNum = $codeNum;
    $this->height = $height;
    $this->width = $width;
    $this->lineFlag = $lineFlag;
    $this->piexFlag = $piexFlag;
    $this->font = dirname(__FILE__).&#39;/fonts/consola.ttf&#39;;
    $this->fontSize = $fontSize;
  }
}
e

font files can be downloaded by the following commands to download below Go to the fonts directory:

$ wget http://labfile.oss.aliyuncs.com/courses/587/consola.ttf

Next, start writing the specific method:


Create image resource handle

//创建图像资源 
public function createImage(){
    $this->img = imagecreate($this->width, $this->height);  //创建图像资源
    imagecolorallocate($this->img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));  //填充图像背景(使用浅色)
  }

Related functions used

imagecreate: Create a new palette-based image

imagecolorallocate: Assign a color to an image

mt_rand: Generate better random numbers

Create a verification code string and output it to the image

//创建验证码 
public function createCode(){
    $strlen = strlen($this->string)-1;
    for ($i=0; $i < $this->codeNum; $i++) {
      $this->code .= $this->string[mt_rand(0,$strlen)];  //从字符集中随机取出四个字符拼接
    }
     $_SESSION[&#39;code&#39;] = $this->code;  //加入 session 中
   
   //计算每个字符间距
    $diff = $this->width/$this->codeNum;
    for ($i=0; $i < $this->codeNum; $i++) {
          //为每个字符生成颜色(使用深色)
     $txtColor = imagecolorallocate($this->img,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
     //写入图像
      imagettftext($this->img, $this->fontSize, mt_rand(-30,30), $diff*$i+mt_rand(3,8), mt_rand(20,$this->height-10), $txtColor, $this->font, $this->code[$i]);
    }
  }

Related functions used

imagecreate: Create a new palette-based image

imagecolorallocate: Assign a color to an image

mt_rand: Generate better random numbers

Create a verification code string And output to the image

//创建验证码 
public function createCode(){
    $strlen = strlen($this->string)-1;
    for ($i=0; $i < $this->codeNum; $i++) {
      $this->code .= $this->string[mt_rand(0,$strlen)];  //从字符集中随机取出四个字符拼接
    }
     $_SESSION[&#39;code&#39;] = $this->code;  //加入 session 中
   
   //计算每个字符间距
    $diff = $this->width/$this->codeNum;
    for ($i=0; $i < $this->codeNum; $i++) {
          //为每个字符生成颜色(使用深色)
     $txtColor = imagecolorallocate($this->img,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
     //写入图像
      imagettftext($this->img, $this->fontSize, mt_rand(-30,30), $diff*$i+mt_rand(3,8), mt_rand(20,$this->height-10), $txtColor, $this->font, $this->code[$i]);
    }
  }

Related functions used:

imagettftext: Use TrueType fonts to write text to the image

Create interference lines

//创建干扰线条(默认四条)
public function createLines(){
    for ($i=0; $i < 4; $i++) {
      $color = imagecolorallocate($this->img,mt_rand(0,155),mt_rand(0,155),mt_rand(0,155));  //使用浅色
      imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
    }
  }

Related functions used:

imageline :Draw a line segment

Create interference points

//创建干扰点 (默认一百个点)
public function createPiex(){
    for ($i=0; $i < 100; $i++) {
      $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
      imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
    }
  }

Related functions used:

imagesetpixel: Draw a single pixel

Output image:

public function show()
 {
   $this->createImage();
   $this->createCode();
   if ($this->lineFlag) {  //是否创建干扰线条
     $this->createLines();
   }
   if ($this->piexFlag) {  //是否创建干扰点
     $this->createPiex();
   }
   header(&#39;Content-type:image/png&#39;);  //请求页面的内容是png格式的图像
   imagepng($this->img);  //以png格式输出图像
   imagedestroy($this->img);  //清除图像资源,释放内存
 }


Related functions used:

imagepng: Output the image to the browser or file in PNG format

imagedestroy: Destroy an image

Provide verification code to the outside world:

public function getCode(){
    return $this->code;
  }

The complete code is as follows:

string = 'qwertyupmkjnhbgvfcdsxa123456789';
    $this->codeNum = $codeNum;
    $this->height = $height;
    $this->width = $width;
    $this->lineFlag = $lineFlag;
    $this->piexFlag = $piexFlag;
    $this->font = dirname(__FILE__).'/fonts/consola.ttf';
    $this->fontSize = $fontSize;
  }
 
  public function createImage(){
    $this->img = imagecreate($this->width, $this->height);
    imagecolorallocate($this->img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
  }
 
  public function createCode(){
    $strlen = strlen($this->string)-1;
    for ($i=0; $i < $this->codeNum; $i++) {
      $this->code .= $this->string[mt_rand(0,$strlen)];
    }
    $_SESSION['code'] = $this->code;
    $diff = $this->width/$this->codeNum;
    for ($i=0; $i < $this->codeNum; $i++) {
      $txtColor = imagecolorallocate($this->img,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
      imagettftext($this->img, $this->fontSize, mt_rand(-30,30), $diff*$i+mt_rand(3,8), mt_rand(20,$this->height-10), $txtColor, $this->font, $this->code[$i]);
    }
  }
 
  public function createLines(){
    for ($i=0; $i < 4; $i++) {
      $color = imagecolorallocate($this->img,mt_rand(0,155),mt_rand(0,155),mt_rand(0,155));
      imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
    }
  }
 
  public function createPiexs(){
    for ($i=0; $i < 100; $i++) {
      $color = imagecolorallocate($this->img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
      imagesetpixel($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
    }
  }
 
  public function show()
  {
    $this->createImage();
    $this->createCode();
    if ($this->lineFlag) {
      $this->createLines();
    }
    if ($this->piexFlag) {
      $this->createPiexs();
    }
    header('Content-type:image/png');
    imagepng($this->img);
    imagedestroy($this->img);
  }
 
  public function getCode(){
    return $this->code;
  }
}

The above is the full code of the verification code class . It does seem quite simple, but it uses a lot of image processing functions. I have also made necessary links and usage instructions for the above related functions. There is no need to memorize these functions by rote. If you encounter something unclear, please refer to the official PHP documentation at any time. The most important thing is that there are Chinese documentation.

2.2 Use verification code


Now that it has been packaged, you can start using it. For convenience here, call this class directly below the Captcha class:

session_start(); //开启session
$captcha = new Captcha();  //实例化验证码类(可自定义参数)
$captcha->show();  //调用输出

3. Front-end display

The back-end has prepared the verification code, and the front-end interface can be displayed. Modify the index.php The verification code part of the registration and login form:

<div class="form-group">
 <div class="col-sm-12">
   <img src="admin/Captcha.php" alt="" id="codeimg" onclick="javascript:this.src = &#39;admin/Captcha.php?&#39;+Math.random();">
   <span>Click to Switch</span>
 </div>
</div>

img tag adds the js code of the click event, so that the function of clicking to change the verification code can be realized!

Rendering:


4. Improvement

Implementing user registration and login function based on PHP

So far, our verification code module is basically completed. After studying here, everyone should have a better understanding of object-oriented programming. I also realized a hint of OOP thinking. The three major characteristics of OOP: encapsulation, inheritance, and polymorphism. We only use a little bit of the idea of ​​encapsulation here. You can continue to refine and improve this verification code class and design a more perfect class. This experiment also tells us that PHP has many functions, so don’t memorize them by rote and read more official documents.


Statement:
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