Home Backend Development PHP Tutorial How to implement random number and letter verification code in php

How to implement random number and letter verification code in php

Jul 13, 2018 am 09:03 AM

PHP implements verification code of random numbers and letters

You can customize the size, quantity, interference items, etc. of the generated verification code text, or you can also customize it. Defines the font for the validation text. . .

Without further ado, let’s go straight to the code:

<?php
Class Captcha{
        private $_fontfile=&#39;&#39;;
        private $_size=36;
        private $_width=200;
        private $_height=100;
        private $_length=4;
        private $_image=null;
        private $_snow=0;
        private $_pixel=0;
        private $_line=0;
    public function __construct($config=array()){
        if(is_array($config)&&count($config)>0){
            if(isset($config[&#39;fontfile&#39;])&&is_file($config[&#39;fontfile&#39;])&&is_readable($config[&#39;fontfile&#39;])){
                $this->_fontfile=$config[&#39;fontfile&#39;];
            }else{
                return false;
            }
            if(isset($config[&#39;size&#39;])&&$config[&#39;size&#39;]>0){
                $this->_size=(int)$config[&#39;size&#39;];
            }
            if(isset($config[&#39;width&#39;])&&$config[&#39;width&#39;]>0){
                $this->_width=(int)$config[&#39;width&#39;];
            }
            if(isset($config[&#39;height&#39;])&&$config[&#39;height&#39;]>0){
                $this->_height=(int)$config[&#39;height&#39;];
            }
            if(isset($config[&#39;length&#39;])&&$config[&#39;length&#39;]>0){
                $this->_length=(int)$config[&#39;length&#39;];
            }
            if(isset($config[&#39;snow&#39;])&&$config[&#39;snow&#39;]>0){
                $this->_snow=(int)$config[&#39;snow&#39;];
            }
            if(isset($config[&#39;pixel&#39;])&&$config[&#39;pixel&#39;]>0){
                $this->_pixel=(int)$config[&#39;pixel&#39;];
            }
            if(isset($config[&#39;line&#39;])&&$config[&#39;line&#39;]>0){
                $this->_line=(int)$config[&#39;line&#39;];
            }
            $this->_image=imagecreatetruecolor($this->_width,$this->_height);
            return $this->_image;

         }
         else{
            return false;
        }
    }
    public function getCaptcha(){
        $white=imagecolorallocate($this->_image,255,255,255);
        imagefilledrectangle($this->_image,0,0,$this->_width,$this->_height,$white);
        $str=$this->_generateStr($this->_length);
        if(false===$str){
            return false;
        }
        $fontfile=$this->_fontfile;
        for($i=0;$i<$this->_length;$i++){
            $size=$this->_size;
            $angle=mt_rand(-30,30);
            $x=ceil($this->_width/$this->_length)*$i+mt_rand(5,10);
            $y=ceil($this->_height/1.5);
            $color=$this->_getRandColor();
            //针对中文字符截取
            //$text=mb_substr($str,$i,1,&#39;utf-8&#39;);
            $text=$str{$i};
            imagettftext($this->_image, $size, $angle, $x, $y, $color, $fontfile, $text);
        }
        if($this->_snow){
            $this->_getSnow();

        }else{
            if($this->_pixel){
                $this->_getPixel();

            }
            if($this->_line){
                $this->_getLine();
            }
        }
        header(&#39;content-type:image/png&#39;);
        imagepng($this->_image);
        imagedestroy($this->_image);
        return strtolower($str);
    }
    private function _getSnow(){
        for($i=1;$i<=$this->_snow;$i++){
            imagestring($this->_image,mt_rand(1,5),mt_rand(0,$this->_width),mt_rand(0,$this->_height),&#39;*&#39;,$this->_getRandColor());
        }
    }
    private function _getPixel(){
        for($i=1;$i<=$this->_pixel;$i++){
            imagesetpixel($this->_image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),$this->_getRandColor());
        }
    }
    private function _getLine(){
        for($i=1;$i<=$this->_line;$i++){
            imageline($this->_image,mt_rand(0,$this->_width),mt_rand(0,$this->_height),mt_rand(0,$this->_width),mt_rand(0,$this->_height),$this->_getRandColor());

        }
    }
    private function _generateStr($length=4){
        if($length<1 || $length>30){
            return false;
        }
        $chars=array(
            &#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;k&#39;,&#39;m&#39;,&#39;n&#39;,&#39;p&#39;,&#39;x&#39;,&#39;y&#39;,&#39;z&#39;,
            &#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;K&#39;,&#39;M&#39;,&#39;N&#39;,&#39;P&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;,
            1,2,3,4,5,6,7,8,9
            );
        $str=join(&#39;&#39;,array_rand(array_flip($chars),$length));
        return $str;
    }
    private function _getRandColor(){
        return imagecolorallocate($this->_image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
    }
}
?>
Copy after login

2. testCaptcha.php

<?php
require_once &#39;classgd.class.php&#39;;
$config=array(
&#39;fontfile&#39;=>&#39;fonts/simfang.ttf&#39;,   //引入字体文件
//&#39;snow&#39;=>50,
&#39;pixel&#39;=>100,
&#39;line&#39;=>10
    );
$captcha=new Captcha($config);
$captcha->getCaptcha();
?>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to rewrite the session storage mechanism in php

How to traverse folders to get pictures through php Directory name and file name

The above is the detailed content of How to implement random number and letter verification code in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles