>  기사  >  백엔드 개발  >  php_php 스킬로 구현한 보안문자 클릭 인증코드 클래스 예시 클릭

php_php 스킬로 구현한 보안문자 클릭 인증코드 클래스 예시 클릭

WBOY
WBOY원래의
2016-05-16 20:35:441115검색

이 글의 예시에서는 클릭 보안 문자 클릭 확인 코드 클래스와 그 사용법을 PHP에서 구현한 매우 실용적인 기능에 대해 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 세부 내용은 다음과 같습니다.

1. 수요:

일반적으로 사용되는 대부분의 양식 확인 코드는 이제 사용자 입력이 필요하지만 이는 모바일 사용자에게는 불편할 것입니다.
모바일 사용자가 방문할 경우, 직접 입력할 필요 없이 특정 위치를 클릭해 인증번호를 확인할 수 있어 훨씬 편리합니다.

2. 원칙:

1. PHP imagecreate를 사용하여 PNG 이미지를 만들고 이미지에 N개의 호를 그립니다. 그 중 하나는 완전한 원입니다(확인용). 그리고 중심 좌표와 반경을 세션에 기록합니다.

2. 브라우저에서 사용자가 인증코드 이미지를 클릭하면 클릭 위치를 기록합니다.

3. 사용자가 클릭한 좌표와 세션에 기록된 중심 좌표 및 반경을 비교하여 원 안에 있는지 확인합니다.

프로그램 실행 효과는 아래와 같습니다.

3. 구현 방법:

ClickCaptcha.class.php 클래스 파일은 다음과 같습니다.

<&#63;php 
/** Click Captcha 验证码类 
*  Date:  2013-05-04 
*  Author: fdipzone 
*  Ver:  1.0 
*/ 
 
class ClickCaptcha { // class start 
 
  public $sess_name = 'm_captcha'; 
  public $width = 500; 
  public $height = 200; 
  public $icon = 5; 
  public $iconColor = array(255, 255, 0); 
  public $backgroundColor = array(0, 0, 0); 
  public $iconSize = 56; 
 
  private $_img_res = null; 
 
  public function __construct($sess_name=''){ 
    if(session_id() == ''){ 
      session_start(); 
    } 
 
    if($sess_name!=''){ 
      $this->sess_name = $sess_name; // 设置session name 
    } 
  } 
 
  /** 创建验证码 */ 
  public function create(){ 
 
    // 创建图象 
    $this->_img_res = imagecreate($this->width, $this->height); 
     
    // 填充背景 
    ImageColorAllocate($this->_img_res, $this->backgroundColor[0], $this->backgroundColor[1], $this->backgroundColor[2]); 
 
    // 分配颜色 
    $col_ellipse = imagecolorallocate($this->_img_res, $this->iconColor[0], $this->iconColor[1], $this->iconColor[2]); 
 
    $minArea = $this->iconSize/2+3; 
 
    // 混淆用图象,不完整的圆 
    for($i=0; $i<$this->icon; $i++){ 
      $x = mt_rand($minArea, $this->width-$minArea); 
      $y = mt_rand($minArea, $this->height-$minArea); 
      $s = mt_rand(0, 360); 
      $e = $s + 330; 
      imagearc($this->_img_res, $x, $y, $this->iconSize, $this->iconSize, $s, $e, $col_ellipse);       
    } 
 
    // 验证用图象,完整的圆 
    $x = mt_rand($minArea, $this->width-$minArea); 
    $y = mt_rand($minArea, $this->height-$minArea); 
    $r = $this->iconSize/2; 
    imagearc($this->_img_res, $x, $y, $this->iconSize, $this->iconSize, 0, 360, $col_ellipse);     
 
    // 记录圆心坐标及半径 
    $this->captcha_session($this->sess_name, array($x, $y, $r)); 
 
    // 生成图象 
    Header("Content-type: image/PNG"); 
    ImagePNG($this->_img_res); 
    ImageDestroy($this->_img_res); 
 
    exit(); 
  } 
 
  /** 检查验证码 
  * @param String $captcha 验证码 
  * @param int  $flag   验证成功后 0:不清除session 1:清除session 
  * @return boolean 
  */ 
  public function check($captcha, $flag=1){ 
    if(trim($captcha)==''){ 
      return false; 
    } 
     
    if(!is_array($this->captcha_session($this->sess_name))){ 
      return false; 
    } 
 
    list($px, $py) = explode(',', $captcha); 
    list($cx, $cy, $cr) = $this->captcha_session($this->sess_name); 
 
    if(isset($px) && is_numeric($px) && isset($py) && is_numeric($py) &&  
      isset($cx) && is_numeric($cx) && isset($cy) && is_numeric($cy) && isset($cr) && is_numeric($cr)){ 
      if($this->pointInArea($px,$py,$cx,$cy,$cr)){ 
        if($flag==1){ 
          $this->captcha_session($this->sess_name,''); 
        } 
        return true; 
      } 
    } 
    return false; 
  } 
 
  /** 判断点是否在圆中 
  * @param int $px 点x 
  * @param int $py 点y 
  * @param int $cx 圆心x 
  * @param int $cy 圆心y 
  * @param int $cr 圆半径 
  * sqrt(x^2+y^2)<r 
  */ 
  private function pointInArea($px, $py, $cx, $cy, $cr){ 
    $x = $cx-$px; 
    $y = $cy-$py; 
    return round(sqrt($x*$x + $y*$y))<$cr; 
  } 
 
  /** 验证码session处理方法 
  * @param  String  $name  captcha session name 
  * @param  String  $value 
  * @return String 
  */ 
  private function captcha_session($name,$value=null){ 
    if(isset($value)){ 
      if($value!==''){ 
        $_SESSION[$name] = $value; 
      }else{ 
        unset($_SESSION[$name]); 
      } 
    }else{ 
      return isset($_SESSION[$name])&#63; $_SESSION[$name] : ''; 
    } 
  } 
} // class end 
 
&#63;> 

demo.php 샘플 프로그램은 다음과 같습니다.

<&#63;php 
session_start(); 
require('ClickCaptcha.class.php'); 
 
if(isset($_GET['get_captcha'])){ // get captcha 
  $obj = new ClickCaptcha(); 
  $obj->create(); 
  exit(); 
} 
 
if(isset($_POST['send']) && $_POST['send']=='true'){ // submit 
  $name = isset($_POST['name'])&#63; trim($_POST['name']) : ''; 
  $captcha = isset($_POST['captcha'])&#63; trim($_POST['captcha']) : ''; 
 
  $obj = new ClickCaptcha(); 
 
  if($obj->check($captcha)){ 
    echo 'your name is:'.$name; 
  }else{ 
    echo 'captcha not match'; 
  } 
  echo ' <a href="demo.php">back</a>'; 
 
}else{ // html 
&#63;> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
 <head> 
 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 
 <title> Click Captcha Demo </title> 
 <script type="text/javascript" src="jquery-1.6.2.min.js"></script> 
 <script type="text/javascript"> 
  $(function(){ 
    $('#captcha_img').click(function(e){ 
      var x = e.pageX - $(this).offset().left; 
      var y = e.pageY - $(this).offset().top; 
      $('#captcha').val(x+','+y); 
    }) 
 
    $('#btn').click(function(e){ 
      if($.trim($('#name').val())==''){ 
        alert('Please input name!'); 
        return false; 
      } 
 
      if($.trim($('#captcha').val())==''){ 
        alert('Please click captcha!'); 
        return false; 
      } 
      $('#form1')[0].submit(); 
    }) 
  }) 
 </script> 
 </head> 
 
 <body> 
  <form name="form1" id="form1" method="post" action="demo.php" onsubmit="return false"> 
  <p>name:<input type="text" name="name" id="name"></p> 
  <p>Captcha:Please click full circle<br><img id="captcha_img" src="demo.php&#63;get_captcha=1&t=<&#63;=time() &#63;>" style="cursor:pointer"></p> 
  <p><input type="submit" id="btn" value="submit"></p> 
  <input type="hidden" name="send" value="true"> 
  <input type="hidden" name="captcha" id="captcha"> 
  </form> 
 </body> 
</html> 
<&#63;php } &#63;> 

이 기사의 전체 소스 코드를 보려면 여기를 클릭하세요이 사이트에서 다운로드하세요.

이 기사가 모든 사람의 PHP 프로그래밍 설계에 도움이 되기를 바랍니다.

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