生成验证码我们会要用到php 图形处理函数,如imagecreate,imagepng,header之类的函数,下面我们一起来看个简单的实例。
实例代码如下:
- <?php
- session_start();
-
- $im = imagecreate(80,30);
- $color = imagecolorallocate($im,rand(150,200),rand(150,200),rand(150,200));
- $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
- for($i=0;$i<5;$i++){
- $code .= $str[rand(0,(strlen($str)-1))];
- }
- $_SESSION['code'] = $code;
- for($a=0;$a<5;$a++){
- $x = $a*10 + 15;
- $y = rand(5,10);
- imagechar($im,5,$x,$y,$code{$a},imagecolorallocate($im,0,0,0));
- }
- header("Content-type:image/png");
- imagepng($im);
- ?>
例2代码如下:
- <?php
- if(!isset($_SESSION)){
- session_start();
- }
- $width=70;
- $height=25;
- $length=4;
- $code=getcode($length);
- $_SESSION['verfyCode'] = $code;
- $img=imagecreate($width,$height);
- $bgcolor=imagecolorallocate($img,240,240,240);
- $rectangelcolor=imagecolorallocate($img,150,150,150);
- imagerectangle($img,1,1,$width-1,$height-1,$rectangelcolor);
- for($i=0;$i<$length;$i++){
- $codecolor=imagecolorallocate($img,mt_rand(50,200),mt_rand(50,128),mt_rand(50,200));
- $angle=rand(-20,20);
- $charx=$i*15+8;
- $chary=($height+14)/2+rand(-1,1);
- imagettftext($img,15,$angle,$charx,$chary,$codecolor,'C:WINDOWSFontsSIMKAI.TTF',
- $code[$i]);
- }
- for($i=0;$i<20;$i++){
- $linecolor=imagecolorallocate($img,mt_rand(0,250),mt_rand(0,250),mt_rand(0,250));
- $linex=mt_rand(1,$width-1);
- $liney=mt_rand(1,$height-1);
- imageline($img,$linex,$liney,$linex+mt_rand(0,4)-2,$liney+mt_rand(0,4)-2,$linecolor);
- }
- for($i=0;$i<100;$i++){
- $pointcolor=imagecolorallocate($img,mt_rand(0,250),mt_rand(0,250),mt_rand(0,250));
- imagesetpixel($img,mt_rand(1,$width-1),mt_rand(1,$height-1),$pointcolor);
- }
- function getcode($length){
- $pattern = '1234567890ABCDEFGHIJKLOMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ';
- for($i=0;$i<$length;$i++) {
- $key .= $pattern{mt_rand(0,35)};
- }
- return $key;
- }
- ob_clean();
- header('Content-type:image/png');
- imagepng($img);
- ?>
(责任编辑:admin) |