1.验证码的显示代码,yanzheng.php
<?php
session_start();
header ('Content-Type: image/png');
$image = imagecreatetruecolor(100, 30) or die('Cannot Initialize new GD image stream'); //生成画布
$bgcolor = imagecolorallocate($image, 255, 255, 255); //图片底色
imagefill($image, 0, 0, $bgcolor);
$vcodes = array(null,null,null,null);
$code = "";
$fontcontent = array();
//生成4位数字
for($i=0;$i<4;$i++){
$fontsize = 6;
$fontcolor = imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$fontcontent[$i] = rand(0,9);
$code.= (string)$fontcontent[$i]; //保存四个数字,点号是连接,string是强制转换类型
$x = ($i*100/4)+rand(5,10);
$y = rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent[$i],$fontcolor); //数字的坐标
}
$_SESSION["Checknum"] = $code; //将随机生成的数字保存到session中,判断的时候用到
//随机加入点
for($i=0;$i<300;$i++){
$pointcolor = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image, rand(1,99),rand(1,99),$pointcolor); //点的位置
}
//随机线
for($i=0;$i<4;$i++){
$linecolor = imagecolorallocate($image, rand(80,220), rand(80,220),rand(80,220));
imageline($image,rand(1,99), rand(1,29),rand(1,99),rand(1,29),$linecolor);//线条的位置
}
imagepng($image); //生成png图片
imagedestroy($image); //销毁
?>
2.调用验证码
<span>验证码:</span><input type="text" size="20" name="check"/>
<img src="yanzheng.php" style="cursor:pointer;"
onclick="javascript:this.src='yanzheng.php?dd'+Math.random()"/>
<span class="pic">点击图片切换</span><br/><span id="show"></span>
3.判断验证码是否正确
<?php
//session_id("Checknum");
session_start();
$code = $_SESSION['Checknum'];//获得随机生成的验证码信息;
if(isset($_POST['check'])){
if(trim($_POST['check'])==""){
echo "<script type=text/javascript>";
echo "document.getElementById('show').innerHTML='请输入验证码'";
echo "</script>";exit();
}
if($code!=trim($_POST['check'])){
echo "<script type=text/javascript>";
echo "document.getElementById('show').innerHTML='验证码输入错误'";
echo "</script>";exit();
}
}
4.效果图
5.参考资料
http://www.imooc.com/learn/115(慕课网的教程,推荐)
http://php.net/manual/zh/index.php(php官网在线参考手册,直接在搜索框搜索各种函数)
http://blog.youkuaiyun.com/rongyongfeikai2/article/details/8769526