简单的php做的一个验证码生成方案

//运行前,你的电脑需要可以运行php的环境,下面,是我的一些做法

//这个是一个运行时的页面

//show.html  ---名字

--------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<img id="code" src="valcode.php"/>  //一个img标签,用来显示验证码的
<span id="change_code" style="cursor:pointer" >看不清</span>  //这是个“看不清”点击键

//极为简单的js代码,如果用jquery将更加简单

<script type="text/javascript"> 
showval();//开始运行时,先执行一次验证码输出

document.getElementById('change_code').onclick=showval;  //点击事件调用


function showval(){  //点击事件
     var numstr="";
    for(i=0;i<4;i++){
        num=Math.round(Math.random()*10);   //随机的4位数
        numstr+=num;
    }
    document.getElementById('code').src='valcode.php?num='+numstr;  //导入到img的src中
}
</script>

</body>

</html>

 -----------------------------------------------------------------
//以上的讲解相当简单吧。那么下面就是php的主要代码了。和我上一章随笔是一样的,只不过变了一点点。下面就是全部代码
//代码的解释和前章随机是一样的,所以没有详细说到,只是部分解释了一下。


//valcode.php   //这是名字

 -------------------------------------------------------------

<?php

header("Content-type:image/png");  //头输出。
$width=80;
$height=42;
$numimage=imagecreate($width, $height);
imagecolorallocate($numimage, 240, 240, 240);


$num=$_GET['num'];   //--------------就是这里了,获得show.html   中最后一行的src ,其中还有个num,用get方法获得就行。

for($i=0;$i<strlen($num);$i++)
{
    $x=mt_rand(0, 10)+$width*$i/4;
    $y=mt_rand(2, $height/3);
    $color=imagecolorallocate($numimage, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255));
    imagestring($numimage, 5, $x, $y, $num{$i}, $color);
}


$color = imagecolorallocate($numimage, 100, 60, 155);
for($i=0;$i<200;$i++){
    imagesetpixel($numimage, mt_rand(0, 80), mt_rand(0, 42), $color);
}
imagepng($numimage);
imagedestroy($numimage);

?>

----------------------------------------------------------

 现在你可以试试看了。

原文地址:https://www.cnblogs.com/wanlxz/p/2627823.html