>  기사  >  백엔드 개발  >  PHP 기반으로 사용자 등록 및 로그인 기능 구현

PHP 기반으로 사용자 등록 및 로그인 기능 구현

高洛峰
高洛峰원래의
2016-12-20 09:17:251993검색

이 글에서는 PHP 기반의 사용자 등록 및 로그인 기능 구현을 소개합니다. 이 프로젝트는 1. 프론트 엔드 페이지 제작, 2. 인증 코드 제작, 3. 등록 및 로그인 구현, 4. 기능적 개선. 자세한 내용은 아래에서 확인하실 수 있습니다.

인증코드 제작

1. 실험 소개

객체지향적 사고를 활용하여 인증코드를 캡슐화하는 실험입니다. 친절한. 등록 및 로그인 인터페이스에 표시됩니다. 본 실험을 통해 PHP의 OOP 개념과 GD 라이브러리의 활용 및 검증코드 생성에 대해 이해하게 될 것입니다.

1.1 관련 지식

PHP

GD 라이브러리

OOP 프로그래밍

1.2 개발 도구

숭고하고 편리하고 빠른 텍스트 편집기입니다. 바탕화면 좌측 하단 클릭: 애플리케이션 메뉴/개발/서브라임

2. 캡슐화 인증코드 클래스

2.1 디렉토리 생성 및 글꼴 준비

백엔드 코드 파일을 저장할 백엔드 디렉토리로 웹 디렉토리에 admin 디렉토리를 만듭니다. 인증 코드 생성에 필요한 글꼴을 저장하려면 admin 아래에 글꼴 디렉터리를 만드세요.

관리자 아래에 새 Captcha.php 파일을 생성합니다. 이것이 우리가 편집해야 할 인증 코드 파일입니다.

현재 디렉토리 계층:

PHP 기반으로 사용자 등록 및 로그인 기능 구현

Captcha.php 파일 편집:

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

이 클래스의 전용 속성과 생성 방법을 추가합니다.

<?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;
  }
}

다음 명령을 통해 글꼴 파일을 글꼴 디렉터리에 다운로드할 수 있습니다. :

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

다음으로 특정 메소드 작성을 시작하세요.

이미지 리소스 핸들 생성

//创建图像资源 
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));  //填充图像背景(使用浅色)
  }

사용된 관련 함수

imagecreate: 새 팔레트 기반 이미지 생성

imagecolorallocate: 이미지에 색상 지정

mt_rand: 더 나은 난수 생성

인증 코드 문자열을 생성하여 이미지에 출력

//创建验证码 
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]);
    }
  }

사용된 관련 기능

imagecreate: 새 팔레트 기반 이미지 생성

imagecolorallocate: 이미지에 색상 할당

mt_rand: 더 나은 생성 난수

인증 코드 문자열을 생성하고 이미지로 출력

//创建验证码 
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]);
    }
  }

사용된 관련 기능:

imagettftext: 사용 이미지에 텍스트를 쓰는 트루타입 글꼴

간섭선 만들기

//创建干扰线条(默认四条)
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);
    }
  }

사용된 관련 기능 :

imageline: 그리기 선분

간섭점 생성

//创建干扰点 (默认一百个点)
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);
    }
  }

사용된 관련 기능:

imagesetpixel: 단일 픽셀 그리기

출력 이미지:

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);  //清除图像资源,释放内存
 }

사용 관련 기능:

imagepng: 이미지를 브라우저에 출력 또는 PNG 형식의 파일

imagedestroy: 이미지 삭제

외부 확인 코드 제공:

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

완료 코드는 다음과 같습니다.

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;
  }
}

위는 모두 인증코드 클래스의 코드입니다. 꽤 간단해 보이지만, 이미지 처리 기능을 많이 사용합니다. 위의 관련 기능에 필요한 링크와 사용 지침도 만들었습니다. 이러한 기능을 암기할 필요는 없습니다. 불분명한 내용이 있으면 언제든지 공식 PHP 문서를 참조하세요. 가장 중요한 것은 중국어 문서가 있다는 것입니다.

2.2 인증코드 사용하기

이제 패키지가 포장되었으므로 사용하실 수 있습니다. 편의상 Captcha 클래스 바로 아래에 이 클래스를 호출합니다.

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

3. 프런트엔드 디스플레이

뒤로 -end 인증 코드가 준비되었으며 index.php에서 등록 및 로그인 양식의 인증 코드 부분을 수정하면 프런트엔드 인터페이스가 표시됩니다.

<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 태그에 클릭 이벤트의 js 코드를 추가하여 인증코드 변경 클릭 기능 구현 가능!

렌더링:

PHP 기반으로 사용자 등록 및 로그인 기능 구현

4. 개선

현재까지 인증코드 모듈은 기본적으로 완료되었습니다. 여기서 공부한 후에는 모든 사람이 객체지향 프로그래밍에 대해 더 잘 이해하게 될 것입니다. 나는 또한 OOP 사고의 힌트를 깨달았습니다. OOP의 세 가지 주요 특징은 캡슐화, 상속, 다형성입니다. 여기서는 캡슐화라는 개념을 약간만 사용합니다. 이 인증코드 클래스를 계속해서 개선하고 개선하여 더욱 완벽한 클래스를 설계할 수 있습니다. 이 실험은 또한 PHP에 많은 기능이 있다는 것을 알려주므로, 이를 암기하지 말고 더 많은 공식 문서를 읽어보세요.


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.