第一步:十六进制数的产生
mt_rand(a.b),随机返回一位介于a~b之间的数字
dechex(a),将数字a转化为十六进制数
随机出现四位十六进制的数字
<?php for($i=0;$i<4;$i++){ $_num.=dechex(mt_rand(0,15)); } echo $_num; ?>
第二步:将随机数字保存在服务器上(跨页面持久)
PHP session它可以把用户提交的数据以全局变量形式保存在一个session中并且会生成一个唯一的session_id,并且session中同一浏览器同一站点只能有一个session_id
<?php $_nmsg=null; for($i=0;$i<4;$i++){ $_nmsg.=dechex(mt_rand(0,15)); } //开启会话 session_start(); $_SESSION["code"]=$_nmsg; ?>输出页面代码
<?php session_start(); echo $_SESSION["code"]; ?>第三步:创建一个图片
<?php$width=75; $height=25;?>//创建图片 $_img=imagecreatetruecolor($width,$height); //白色背景 $_white=imagecolorallocate($_img,255,255,255); imagefill($_img,0,0,$_white); //随机颜色的边框 $_randbordercolor=false; if( $_randbordercolor){ $_randcolor=imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imagerectangle($_img,0,0,$width-1,$height-1,$_randcolor); } //随机画线条 for($i=0;$i<6;$i++){ $_linecolor=imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imageline($_img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$_linecolor); } //随机雪花 for($i=0;$i<100;$i++){ $_linecolor=imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imagestring($_img,1,mt_rand(0,$width),mt_rand(0,$height),'*',$_linecolor); } //输出随机数 for($i=0;$i<strlen($_SESSION['code']);$i++){ $_linecolor=imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)); imagestring($_img,mt_rand(3,5),$i*$width/$_randnum+mt_rand(1,10),mt_rand(0,$height/2),$_SESSION['code'][$i],$_linecolor); } //输出图像 header('Content-Type:image/png'); imagepng($_img); //图片销毁 imagedestory($_img);
第五步:页面调用
code.php已经生成一张图片,直接用图片插入的方式即可<img src="code.php" />
解释说明:1. strlen()函数是求数组长度,$_SESSION['code']可以按照数组的形式进行访问。
2.必须在页面输出图像,才能看到图片