Home  >  Article  >  Backend Development  >  PHP generates image verification code and click switching code

PHP generates image verification code and click switching code

不言
不言Original
2018-06-21 10:17:553070browse

This article mainly introduces the example of PHP generating image verification code, and also introduces the method to achieve the effect of clicking to switch (can't see clearly? Change one). Friends in need can refer to it

Here to take a look Effect:

Now let us take a look at the PHP code

<?php
 
session_start();
function random($len) {
    $srcstr = "1a2s3d4f5g6hj8k9qwertyupzxcvbnm";
    mt_srand();
    $strs = "";
    for ($i = 0; $i < $len; $i++) {
        $strs .= $srcstr[mt_rand(0, 30)];
    }
    return $strs;
}
 
//随机生成的字符串
$str = random(4); 
 
//验证码图片的宽度
$width  = 50;      
 
//验证码图片的高度
$height = 25;     
 
//声明需要创建的图层的图片格式
@ header("Content-Type:image/png");
 
//创建一个图层
$im = imagecreate($width, $height);
 
//背景色
$back = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
 
//模糊点颜色
$pix  = imagecolorallocate($im, 187, 230, 247);
 
//字体色
$font = imagecolorallocate($im, 41, 163, 238);
 
//绘模糊作用的点
mt_srand();
for ($i = 0; $i < 1000; $i++) {
    imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pix);
}
 
//输出字符
imagestring($im, 5, 7, 5, $str, $font);
 
//输出矩形
imagerectangle($im, 0, 0, $width -1, $height -1, $font);
 
//输出图片
imagepng($im);
 
imagedestroy($im);
 
$str = md5($str);
 
//选择 cookie
//SetCookie("verification", $str, time() + 7200, "/");
 
//选择 Session
$_SESSION["verification"] = $str;
?>

Then just call it in the page:

<img id="checkpic" onclick="changing();" src=&#39;/images/checkcode.php&#39; />

If you want to achieve "cannot see Clear? Change one" effect, add the following JS to the page

function changing(){
    document.getElementById(&#39;checkpic&#39;).src="/images/checkcode.php?"+Math.random();
}

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

Related recommendations:

How to use PHP to dynamically generate copyright information

How to use PHP code to implement WeChat jump One hop

The above is the detailed content of PHP generates image verification code and click switching code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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