Рубрики
Uncategorized

Пример операции проверки кода с помощью ползунка перетаскивания, реализованной с помощью PHP + JS

Автор оригинала: David Wong.

В этой статье описывается реализация PHP + JS кода проверки слайдера перетаскивания для проверки работы формы. Для вашей справки приведем следующие сведения:

Сейчас многие веб-сайты, такие как Taobao и Jingdong, используют проверочный код polar для входа в систему. Этот метод имеет лучший опыт, чем традиционный метод проверки кода, уменьшает количество ошибок при вводе пользователем, а также может выполнять функцию противоугонной щетки. В настоящее время многие из них являются сторонними, и многие из них являются платными. Сегодня я хотел бы поделиться с вами экстремальным тестовым кодом, реализованным с использованием собственного PHP. Преимущество использования собственного PHP заключается в том, что вы можете напрямую использовать основной код для изменения структуры, в которую вы хотите встроиться.

Анимация перетаскивания полярного опыта

Скриншот файла кода

реализация кода

HTML-файл





  
  
  
  < title > polar verification slider drag verification code code code code community web video sharing network
  
  



Файл PHP: проверьте. php

check()){
    $_SESSION['tncode_check'] = 'ok';
  echo "ok";
}else{
    $_SESSION['tncode_check'] = 'error';
  echo "error";
}

?>

Основные основные документы: TnCode.class.php

_init();
    $this->_createSlide();
    $this->_createBg();
    $this->_merge();
    $this->_imgout();
    $this->_destroy();
  }

  function check($offset=''){
    if(!$_SESSION['tncode_r']){
      return false;
    }
    if(!$offset){
      $offset = $_REQUEST['tn_r'];
    }
    $ret = abs($_SESSION['tncode_r']-$offset)<=$this->_fault;
    if($ret){
      unset($_SESSION['tncode_r']);
    }else{
      $_SESSION['tncode_err']++;
      if($_ SESSION['tncode_ Err '] > 10) {// error 10 times must be refreshed
        unset($_SESSION['tncode_r']);
      }
    }
    return $ret;
  }

  private function _init(){
    $bg = mt_rand(1,$this->bg_num);
    $file_bg = dirname(__FILE__).'/bg/'.$bg.'.png';
    $this->im_fullbg = imagecreatefrompng($file_bg);
    $this->im_bg = imagecreatetruecolor($this->bg_width, $this->bg_height);
    imagecopy($this->im_bg,$this->im_fullbg,0,0,0,0,$this->bg_width, $this->bg_height);
    $this->im_slide = imagecreatetruecolor($this->mark_width, $this->bg_height);
    $_SESSION['tncode_r'] = $this->_x = mt_rand(50,$this->bg_width-$this->mark_width-1);
    $_SESSION['tncode_err'] = 0;
    $this->_y = mt_rand(0,$this->bg_height-$this->mark_height-1);
  }

  private function _destroy(){
    imagedestroy($this->im);
    imagedestroy($this->im_fullbg);
    imagedestroy($this->im_bg);
    imagedestroy($this->im_slide);
  }
  private function _imgout(){
    if(!$_ GET['nowebp']&&function_ Exists ('imagewebp ')) {// preferred webp format, ultra-high compression ratio
      $type = 'webp';
      $quality = 40; // picture quality 0-100
    }else{
      $type = 'png';
      $quality = 7; // picture quality 0-9
    }
    header('Content-Type: image/'.$type);
    $func = "image".$type;
    $func($this->im,null,$quality);
  }
  private function _merge(){
    $this->im = imagecreatetruecolor($this->bg_width, $this->bg_height*3);
    imagecopy($this->im, $this->im_bg,0, 0 , 0, 0, $this->bg_width, $this->bg_height);
    imagecopy($this->im, $this->im_slide,0, $this->bg_height , 0, 0, $this->mark_width, $this->bg_height);
    imagecopy($this->im, $this->im_fullbg,0, $this->bg_height*2 , 0, 0, $this->bg_width, $this->bg_height);
    imagecolortransparent($this->im,0);//16777215
  }

  private function _createBg(){
    $file_mark = dirname(__FILE__).'/img/mark.png';
    $im = imagecreatefrompng($file_mark);
    header('Content-Type: image/png');
    //imagealphablending( $im, true);
    imagecolortransparent($im,0);//16777215
    //imagepng($im);exit;
    imagecopy($this->im_bg, $im, $this->_x, $this->_y , 0 , 0 , $this->mark_width, $this->mark_height);
    imagedestroy($im);
  }

  private function _createSlide(){
    $file_mark = dirname(__FILE__).'/img/mark2.png';
    $img_mark = imagecreatefrompng($file_mark);
    imagecopy($this->im_slide, $this->im_fullbg,0, $this->_y , $this->_x, $this->_y, $this->mark_width, $this->mark_height);
    imagecopy($this->im_slide, $img_mark,0, $this->_y , 0, 0, $this->mark_width, $this->mark_height);
    imagecolortransparent($this->im_slide,0);//16777215
    //header('Content-Type: image/png');
    //imagepng($this->im_slide);exit;
    imagedestroy($img_mark);
  }

}
?>

Вложение: Полный код экземпляра нажмите здесь Скачать с этого веб-сайта

Более заинтересованные читатели, интересующиеся контентом, связанным с PHP, могут просмотреть специальные разделы этого веб-сайта: “Краткое изложение навыков работы с графикой и изображениями PHP”, “Навыки работы с массивом PHP (массив)”, “Учебник по структуре данных и алгоритмам PHP”, “Краткое изложение алгоритмов программирования PHP”, “Краткое изложение навыков математических операций PHP”, “Краткое изложение использования строк PHP” и “Краткое изложение навыков работы с общими базами данных PHP” “

Я надеюсь, что эта статья поможет вам в программировании на PHP.