>  기사  >  백엔드 개발  >  PHP에서 산술 인증 코드를 구현하는 방법

PHP에서 산술 인증 코드를 구현하는 방법

不言
不言원래의
2018-07-05 15:04:562375검색

이 글은 주로 PHP에서 산술 검증 코드를 구현하는 방법을 소개합니다. 이제 특정 참조 가치가 있습니다. 이제 모든 사람들과 공유합니다. 도움이 필요한 친구들은 그것을 참조할 수 있습니다

최근에 PHP의 이미지 기능도 배웠습니다. 이를 구현하기 위해 선생님의 제안에 따라 산술 인증 코드에 대한 함수를 작성해 보았습니다. 작은 연습을 독립적으로 완료하는 것이 처음이었지만 제 자신의 한계도 알고 있었기 때문에 매우 기뻤습니다. 특별히 작성했습니다. Master Lu의 안내를 받아 시야를 더 넓힐 수 있습니다

php 코드는 다음과 같습니다: 인증 코드 기능 구현

<?php/**
 * @param int $width 宽度,默认为120
 * @param int $height 高度,默认为50
 * @param int $fontSize 字体的大小
 * @return 图片资源
 */function arithmeticCode($width=120,$height=50,$fontSize=20){
    //开启session
    session_start();    //创建画布
    $img = imagecreatetruecolor($width,$height);    //分配颜色
    $color = imagecolorallocate($img,255,255,255);    //填充颜色
    imagefill($img,0,0,$color);    //干扰点
    for ($i = 0;$i < 500;$i++){        $pixColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
        imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixColor);
    }    //干扰线
    for ($i = 0;$i < 4;$i++){        $lineColor = imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
        imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$lineColor);
    }    //定义一个数组存放运算符号
    $arr = [&#39;+&#39;,&#39;-&#39;,&#39;*&#39;];    //计算数组的长度
    $len = count($arr);    //定义一个1到20的数组
    $num = range(1,20);    $numLen = count($num);    //定义一个空数组来存放随机取得的验证码
    $code = [];    for ($i = 0;$i < $len;$i++) {        if ($i == 1) {            $code[] = $arr[mt_rand(0,$len-1)];
        }else {            $code[] = $num[mt_rand(0,$numLen-1)];
        }
    }    $str = implode($code);//将数组转为字符串
    $textColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));    $fontAngle = 0;    $x = ($width - $fontSize*3)/2;    $y = ($height - $fontSize) / 2 + $fontSize;
    imagettftext($img,$fontSize,$fontAngle,$x,$y,$textColor,"./img/msyh.ttc",$str);    $res = getRes($code);    //将函数存放在session中
    $_SESSION[&#39;res&#39;] = $res;    //输出图片
    header("content-type:image/png");
    imagepng($img);
}/**
 * @param $arr 一个包含运算符号的数组
 * @return 返回一个运算结果
 */function getRes($arr) {
    $sum = 0;    //判断数组元素下标为1的运算符号是什么
    switch ($arr[1]){        case &#39;+&#39;:            $sum = $arr[0] + $arr[2];            break;        case &#39;-&#39;:            $sum = $arr[0] - $arr[2];            break;        case &#39;*&#39;:            $sum = $arr[0] * $arr[2];            break;
    }    return $sum;
}//调用函数arithmeticCode(100,40,18);

html 코드의 일부

<!doctype html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {            position: relative;            top: 20px;        }
    </style></head><body><form action="test.php">
    验证码 <input type="text" name="code">
    <img src="./demo5.php" alt="点击刷新">
    <br>
    <button>提交</button></form></body></html><script>
    //实现点击图片刷新验证码的功能
    var img = document.querySelector("img");
    img.onclick = function () {
        this.src = this.src+"?m="+Math.random();
    }</script>

test.php test

<?phpsession_start();$res = $_SESSION[&#39;res&#39;];$value = $_GET[&#39;code&#39;];if ($res == $value) {    echo "test success";
}else{    echo "test fail";
}

위는 제가 작성한 코드의 구성입니다.
모든 마스터들이 조언을 해주셨으면 좋겠습니다. [기대됩니다]

위 내용은 이 글의 전체 내용입니다. 모든 분들의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용을 보시려면 PHP 중국어 웹사이트를 주목해주세요!

관련 권장 사항:

PHP7에서 MongoDB 드라이버 사용 소개

PHP에서 배열의 값을 변수 집합에 할당하는 방법

위 내용은 PHP에서 산술 인증 코드를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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