>  기사  >  백엔드 개발  >  클래식 PHP 확인 코드 클래스 Sharing_php 예

클래식 PHP 확인 코드 클래스 Sharing_php 예

WBOY
WBOY원래의
2016-05-16 20:31:41879검색

우리는 PHP의 GD 라이브러리를 사용하여 콘텐츠를 이미지 처리하고 확인 코드 클래스 Vcode를 설계합니다. vcode.class.php 파일에서 이 클래스를 선언하고 객체 지향 기능을 통해 이 클래스의 일부 구현 세부 사항을 캡슐화합니다. 생성된 인증코드 이미지의 너비와 높이, 인증코드 글자 수 등 객체 생성 시 생성자에 3개의 파라미터를 제공하기만 하면 인증코드 클래스의 객체를 성공적으로 생성할 수 있습니다. 이 클래스의 선언 코드는 다음과 같습니다.

<&#63;php
 class Vcode {
  private $width; //宽
  private $height; //高
  private $num;  //数量
  private $code; //验证码
  private $img;  //图像的资源
 
  //构造方法, 三个参数
  function __construct($width=80, $height=20, $num=4) {
   $this->width = $width;
   $this->height = $height;
   $this->num = $num;
   $this->code = $this->createcode(); //调用自己的方法
  }
 
  //获取字符的验证码, 用于保存在服务器中
  function getcode() {
   return $this->code;
  }
 
  //输出图像
  function outimg() {
   //创建背景 (颜色, 大小, 边框)
   $this->createback();
 
   //画字 (大小, 字体颜色)
   $this->outstring();
 
   //干扰元素(点, 线条)
 
   $this->setdisturbcolor();
   //输出图像
   $this->printimg();
  }
 
  //创建背景
  private function createback() {
   //创建资源
   $this->img = imagecreatetruecolor($this->width, $this->height);
   //设置随机的背景颜色
   $bgcolor = imagecolorallocate($this->img, rand(225, 255), rand(225, 255), rand(225, 255)); 
   //设置背景填充
   imagefill($this->img, 0, 0, $bgcolor);
   //画边框
   $bordercolor = imagecolorallocate($this->img, 0, 0, 0);
 
    imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $bordercolor);
  }
 
  //画字
  private function outstring() {
   for($i=0; $i<$this->num; $i++) {
 
    $color= imagecolorallocate($this->img, rand(0, 128), rand(0, 128), rand(0, 128)); 
 
    $fontsize=rand(3,5); //字体大小
 
    $x = 3+($this->width/$this->num)*$i; //水平位置
    $y = rand(0, imagefontheight($fontsize)-3);
 
    //画出每个字符
    imagechar($this->img, $fontsize, $x, $y, $this->code{$i}, $color);
   }
  }
 
  //设置干扰元素
  private function setdisturbcolor() {
   //加上点数
   for($i=0; $i<100; $i++) {
    $color= imagecolorallocate($this->img, rand(0, 255), rand(0, 255), rand(0, 255)); 
    imagesetpixel($this->img, rand(1, $this->width-2), rand(1, $this->height-2), $color);
   }
 
   //加线条
   for($i=0; $i<10; $i++) {
    $color= imagecolorallocate($this->img, rand(0, 255), rand(0, 128), rand(0, 255)); 
    imagearc($this->img,rand(-10, $this->width+10), rand(-10, $this->height+10), rand(30, 300), rand(30, 300), 55,44, $color);
   }
  }
 
  //输出图像
  private function printimg() {
   if (imagetypes() & IMG_GIF) {
     header("Content-type: image/gif");
     imagegif($this->img);
   } elseif (function_exists("imagejpeg")) {
     header("Content-type: image/jpeg");
     imagegif($this->img);
   } elseif (imagetypes() & IMG_PNG) {
     header("Content-type: image/png");
     imagegif($this->img);
   } else {
     die("No image support in this PHP server");
   } 
 
  }
 
  //生成验证码字符串
  private function createcode() {
   $codes = "3456789abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY";
 
   $code = "";
 
   for($i=0; $i < $this->num; $i++) {
    $code .=$codes{rand(0, strlen($codes)-1)}; 
   }
 
   return $code;
  }
 
  //用于自动销毁图像资源
  function __destruct() {
   imagedestroy($this->img);
  }
 
 }

위 스크립트에는 인증 코드 클래스 Vcode를 선언하는 코드가 많지만, 개체가 직접 출력되는 한 세부 사항은 모두 클래스에 캡슐화되어 있으므로 클라이언트 브라우저에 그림이 출력될 수 있습니다. 도구 형태로 이용하여 찾아볼 수 있습니다. 또한 이 클래스는 인증 코드 이미지의 문자열을 자동으로 얻어 서비스의 $_SESSION["code"]에 저장합니다. 양식을 제출할 때 사용자가 양식에 인증 코드 이미지에 표시된 텍스트를 입력하고 서버에 보관된 인증 코드 문자열과 정확히 일치하는 경우에만 양식을 성공적으로 제출할 수 있습니다. (참고: 인증코드는 서버 측 $_SESSION["code"]에 있으므로 이 클래스를 사용하려면 세션을 열어야 합니다.)

다음 스크립트 code.php에서 session_start()를 사용하여 사용자 세션 제어를 활성화한 다음 확인 코드 클래스 Vcode가 있는 vcode.class.php 파일을 포함하고 이 유형의 객체를 생성하여 직접 출력합니다. 무작위로 생성된 인증코드 이미지를 전송할 수 있으며, 인증코드 문자열은 자동으로 서버에 저장됩니다. 코드는 다음과 같습니다.

<&#63;php
 //开启session
 session_start();
 include "vcode.class.php";
 //构造方法
 $vcode = new Vcode(80, 30, 4);
 //将验证码放到服务器自己的空间保存一份
 $_SESSION['code'] = $vcode->getcode();
 //将验证码图片输出
 $vcode->outimg();
&#63;>

양식 코드는 다음과 같습니다.

<&#63;php
 session_start();
if(isset($_POST['dosubmit'])) {
 if(strtoupper($_SESSION['code']) == strtoupper($_POST['code']) ) {
  echo "输入成功!<br>";
 }else{
  echo "输入不对!<br>";
 }
}
&#63;>
 
<body>
 <form action="reg.php" method="post">
  username: <input type="text" name="username"> <br>
  password: <input type="password" name="password"> <br>
  code: <input type="text" onkeyup="if(this.value!=this.value.toUpperCase()) this.value=this.value.toUpperCase()" size="6" name="code"> 
    <img src="code.php" onclick="this.src='code.php&#63;'+Math.random()" /> <br>
  <input type="submit" name="dosubmit" value="登 录"> <br>
 </form>
</body>

PHP 클래식 인증코드 다운로드:

PHP 인증코드 class.rar

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