PHP GD 生成圖片驗證碼+session獲取儲存驗證碼
以下分享一個PHP制作的圖片驗證碼案例:案比例如以下圖:
運用PHP GD具體請看:http://www.php.net/manual/zh/book.image.php
後臺圖片代碼例如以下:
<?php session_start(); $image = imagecreatetruecolor(100,30);//創建一個寬100。高度30的圖片 $bgcolor=imagecolorallocate($image,255,255,255);//圖片背景是白色 imagefill($image,0,0,$bgcolor);//圖片填充白色 //隨機數 /** for($i=0;$i<4;$i++){ $fontsize=6; $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); $fontcontent=rand(0,9); $x=($i*100/4)+ rand(5,10); $y=rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } **/ //隨機數據 $captch_code=''; for($i=0;$i<4;$i++){ $fontsize=6; $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); $data='asdfdfglfg74erf21854hgfhgfhkg4ljkghjtrtywiqpoqpwepdfgvnjytyut12313345645667686797800'; $fontcontent=substr($data,rand(0,strlen($data)),1); $captch_code.=$fontcontent; $x=($i*100/4)+ rand(5,10); $y=rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } $_SESSION['authcode']=$captch_code; //隨機點 for($i=0;$i<200;$i++){ $pointcolor=imagecolorallocate($image,rand(50,120),rand(50,120),rand(50,120)); imagesetpixel($image,rand(1,99),rand(1,99),$pointcolor); } //隨機線 for($i=0;$i<3;$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); } header("content-type:image/png"); imagepng($image); imagedestory($image); ?>
前臺代碼例如以下:
<?php if(isset($_REQUEST['autocode'])){ session_start(); if(strtolower($_POST['autocode']) == $_SESSION['authcode']){ echo '正確'; }else{ echo'錯誤'; } exit(); } ?> <!DOCTYPE html> <html> <head> <meta chartset="utf-8"> </head> <body> <form method="post" action="form.php"> <p>驗證碼圖片:<img border="1" src="captcha.php?r="<?php echo rand();?> width="100" height="30" /></p> <p>輸入內容:<input type="text" name="autocode" value="" /></p> <p><input type="submit" value="提交" style="padding:6px 20px;"/></p> </form> </body> </html>
加入點擊運行改動例如以下就可以:
<p>驗證碼圖片:<img border="1" id="capthcha_img" onclick="this.src='captcha.php?r='+Math.random()" src="captcha.php?r="<?
php echo rand();?> width="100" height="30" /> <a href="javascript:void(0)" onclick="document.getElementById('capthcha_img').src='captcha.php?
r='+Math.random()">換一個</a></p>
本案例原創,轉載請註明。
PHP GD 生成圖片驗證碼+session獲取儲存驗證碼