今天做个验证码用于登录,很简单,接下来开始写:
验证码绘画流程:
1.创建图像资源(创建一个画布)
2.选择颜色,然后给画布填充颜色(默认的画布是黑色)
3.给画笔分配颜色
4.开始绘制
5.输出到浏览器或保存到本地(选择位置)
6.销毁图像资源
需要用到的函数:
imagecreatetruecolor(resource $image1 , resource $image2)---新建一个真彩色图像 imagecolorallocate( resource $image , int $red , int $green , int $blue)---为一幅图像分配颜色 imagefill(resource $image , int $x , int $y , int $color) — 区域填充分配颜色
imagestring(resource $image , int $font , int $x , int $y , string $s , int $col) — 水平地画一行字符串
接下来创建一个Captcha.php文件,里面的代码如下:
session_start(); //创建图像资源 $img = imagecreatetruecolor(100,30); //选择颜色 $color = imagecolorallocate($img,255,0,255); //填充颜色 imagefill($img,0,0,$color); //填充字符串 $string = "ABCDEFGabcdefg123569"; $char = ''; //定义一个变量,给SESSION传值 for($i=1;$i<=4;$i++){ //给字符串分配区域 $int = substr($string, mt_rand(0, strlen($string)-1), 1); //在$string中随机生成1个 $char .= $int; //设置颜色 $fontColor = imagecolorallocate($img,mt_rand(0,100),mt_rand(100, 150), mt_rand(0, 255)); $x = ($i*100)/4-15; //设置X轴 $y = mt_rand(5,10); //设置Y轴 /** imagestring的6个参数 * 1.图像资源 * 2.字体的大小 * 3.横坐标 * 4.纵坐标 * 5.字符串 * 6.字符串颜色 */ imagestring($img, 5, $x, $y, $int, $fontColor); } $_SESSION['yzm'] = $char; //发送头信息,告诉浏览器是图像 header('Content-Type:image/png'); //输出到浏览器或保存到本地(选择位置) //imagepng( resource $image [, string $filename ]) — 以 PNG 格式将图像输出到浏览器或文件 imagepng($img); //销毁图像资源 imagedestroy($img);
在创建一个index.php文件,展示页面
<?php //展示页面 session_start(); if($_POST){ //session里的验证码等于提交的验证码 if(strtolower($_SESSION['yzm']) === strtolower($_POST['yzm'])){ echo 'Cominf in' ; } } ?> <!DOCTYPE html> <html> <head> <title>hahha</title> <meta charset="utf-8"> </head> <body> <form action="" method="post"> 验证码: <input type="text" name="yzm"> <img src="yanzhengma.php" alt=""><br/> <input type="submit" value="提交" name="sub"/> </form> </body>
//这里的js代码是点击验证码就会刷新的效果 <script type="text/javascript"> var Oimg = document.getElementById('img'); Oimg.onclick = function(){ this.src = "yanzhengma.php?"+Math.random(); } </script> </html>
展示效果: