>  기사  >  백엔드 개발  >  PHP를 기반으로 사용자 등록 및 로그인 기능을 구현하는 방법

PHP를 기반으로 사용자 등록 및 로그인 기능을 구현하는 방법

墨辰丷
墨辰丷원래의
2018-06-01 09:25:231579검색

이 과정은 PHP와 웹 프런트엔드 기술을 사용하여 웹사이트 등록 및 로그인 입력 페이지를 구현하고, PHP 프로그래밍을 배우고 연습하는 등 관심 있는 학생들이 참고할 수 있습니다.

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

인증코드 생성

1. 실험 소개

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

1.1 관련 지식 포인트

  • PHP

  • GD 라이브러리

  • OOP 프로그래밍

1.2 개발 도구

sublime, 그리고 빠른 텍스트 편집기. 데스크탑 왼쪽 하단을 클릭하세요: 애플리케이션 메뉴/Development/sublime

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

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

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

관리자 아래에 새 Captcha.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: 트루타입 글꼴을 사용하여 이미지에 쓰기 Text

간섭선 만들기

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

사용된 관련 기능 :

  • 이미지 세트픽셀: 단일 픽셀 그리기

출력 이미지:

 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;
  }
完整代码如下:
<?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;
  }

  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[&#39;code&#39;] = $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(&#39;Content-type:image/png&#39;);
    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. 프런트 엔드 표시

백엔드에서 인증 코드를 준비했으며, 프런트 엔드 인터페이스가 표시될 수 있습니다. index.php 수정 등록 및 로그인 양식의 인증 코드 부분:

<p class="form-group">
 <p 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>
 </p>
</p>

img 태그는 클릭 이벤트의 js 코드를 추가하여 인증 코드를 변경하기 위해 클릭하는 기능을 구현할 수 있습니다!

렌더링:


4. 개선

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

요약: 위 내용은 이 글의 전체 내용입니다. 모든 분들의 공부에 도움이 되었으면 좋겠습니다.

관련 추천:

php WeChat 결제로 현금 빨간 봉투를 실현하세요

thinkPHP 자동 확인, 자동 추가 및 양식 오류 세부 정보

위 내용은 PHP를 기반으로 사용자 등록 및 로그인 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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