当前位置 : 主页 > 网络编程 > PHP >

Captcha.php

来源:互联网 收集:自由互联 发布时间:2021-06-28
Captcha.php codeNum = $codeNum; $this-width = $width; $this-height = $height; $this-lineFlag = $lineFlag; $this-pixelFlag = $piexFlag; $this-fontSize = $fontSize; $this-string = 'qwertyupmkjnhbgvfcdsxa123456789'; $this-font = dirname(__FILE
Captcha.php
 codeNum = $codeNum;
        $this->width = $width;
        $this->height = $height;
        $this->lineFlag = $lineFlag;
        $this->pixelFlag = $piexFlag;
        $this->fontSize = $fontSize;
        $this->string = 'qwertyupmkjnhbgvfcdsxa123456789';
        $this->font = dirname(__FILE__) . '/fonts/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));
    }

    public function createCode()
    {
        $strlen = strlen($this->string) - 1;
        for ($i = 0; $i < $this->codeNum; $i++) {
            $this->code .= $this->string[mt_rand(0, $strlen)];
        }

        $_SESSION['code'] = $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 createPixel()
    {
        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->pixelFlag) {
            $this->createPixel();
        }
        header('Content-type;image/png');
        imagepng($this->img);
        imagedestroy($this->img);
    }

    public function getCode() {
        return $this->code;
    }

    public function getFont() {
        return $this->font;
    }
}

session_start();
$captcha = new Captcha();
$captcha->show();
网友评论