首先保证开启PHP的GD库 然后
代码如下
<?php session_start(); for($i=0;$i<6;$i++) { //$shui=rand(0,15); //echo dechex($shui);//dechex函数十六进制可以把十进制转换成字母 $shui.=dechex(rand(1,15)); } $_SESSION[check_pic]=$shui; $im=imagecreatetruecolor(100,30);//创建一个真彩色图片,宽100px,高30px //创建颜色 $bg=imagecolorallocate($im,0,0,0);//第一次用调试板时为背景颜色,000为黑色 $te=imagecolorallocate($im,255,255,255);//255,255,255为白色 // 画干扰线 for($i=0;$i<4;$i++) { $te2=imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));//255,255,255为白色 imageline($im,0,rand(0,20),100,rand(0,30),$te2); } //画噪点 for($i=0;$i<200;$i++) { imagesetpixel($im,rand(0,100),rand(0,30),$te2); } //把字符串写在图片左上角 imagestring($im,rand(4,6),rand(3,40),rand(3,10),$shui,$te); //输出图片 header('Content-type:image/jpeg'); imagejpeg($im); imagedestroy($im); ?>
调用代码如下:
<?php session_start(); if($_POST['check']) { if($_POST['check']==$_SESSION['check_pic']) { echo '验证码正确',$_SESSION['check_pic']; } else{echo '验证码错误',$_SESSION['check_pic'];} } ?> <form action="" method="post"> <img src="getcode.php" mce_src="getcode.php"><br/> <input type="text" name="check" maxlength="4"> <input type="submit" value="提交"> </form>
基本原理如此!