標籤:nbsp void str div 語言 字型 20px inf 實現
項目中經常會遇到一些登陸驗證,支付驗證等等一系列安全驗證的策略。實現方法多種多樣,下面就來講解下如何用php產生簡單的文字+數字組合的驗證碼:
所用語言php,gd庫
原理解釋:
a>實質上是在伺服器端隨機產生驗證碼,將其儲存在$_SESSION中。
b>然後將驗證碼寫在圖片上,將圖片發送至用戶端,使用者輸入圖片的上的驗證碼,遞交給伺服器。
c>服務端再與$_SESSION中儲存的資訊比對,一致則通過,否則不通過。
分為兩步:
1)第一步伺服器端產生驗證碼
2)用戶端使用驗證碼
第一步:在伺服器端如何產生驗證碼:<code.php>
<?phpsession_start();
//1>session_start()必須置於最頂部,2>多伺服器,要考慮集中管理session資訊 //phpinfo();//列印出php的資訊
//1.產生一張底圖(width:100;height:30)$image=imagecreatetruecolor(100,30);$bgcolor=imagecolorallocate($image,255,255,255);//畫筆著色imagefill($image,0,0,$bgcolor);//將底圖的著色//隨機產生四個數字/*for($i=0;$i<4;$i++){ $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120)); $fontcontent=rand(0,9);//驗證碼的內容 $fontsize=6;//字型大小 $x=($i*100/4)+rand(5,10);//x軸 $y=rand(5,10);//Y軸 imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);//使用imagestring()將文字寫在畫布上}*/$captch_code="";for($i=0;$i<4;$i++){ $fontsize=6; $fontcolor=imagecolorallocate($image,rand(20,100),rand(30,100),rand(10,200)); $str="abcdefghkmnpwsert1234567890";//給出一個字串,用於產生隨機驗證碼 $fontcontent=substr($str,rand(0,strlen($str)),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;//儲存在session中//添加幹擾點for($i=0;$i<100;$i++){ $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); imagesetpixel($image,rand(0,100),rand(0,30),$pointcolor);}//添加幹擾線for($i=0;$i<3;$i++){ $linecolor=imagecolorallocate($image,rand(80,200),rand(80,200),rand(80,200)); imageline($image,rand(5,95),rand(5,25),rand(5,95),rand(5,25),$linecolor);}header("content-type:".‘image/png‘);//輸出圖片的標頭檔固定格式(可以是image/jpg、image/png、)imagepng($image);//向瀏覽器輸出一張圖片imagedestroy($image);//銷毀記憶體中的底圖//session_start
第二步:將產生的驗證碼圖片返回給用戶端<form.php>
<?phpheader("Content-type:text/html;charset=utf-8");if(isset($_REQUEST[‘authcode‘])){ session_start();//使用$_SESSION之前必須使用session_start() if(strtolower($_REQUEST[‘authcode‘])==$_SESSION["authcode"]){//$_SESSION[‘authcode‘]是伺服器端儲存的驗證碼,$_REQUEST[‘authcode‘]擷取用戶端輸入的資訊 echo "<font color=‘#000cc‘>輸入正確</font>"; } else{ echo "<font color=‘#0000cc‘>輸入錯誤</font>"; } exit();}?><!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>驗證碼正確</title> </head></html><body> <form action="./form.php"> <p>驗證碼圖片:
//點擊驗證碼圖片本身進行驗證碼的切換(需求一) //產生隨機數字,便於訪問服務端,如果地址是相同的則瀏覽器不會重新整理訪問 <img id="captCode" src="./code.php?=<?php echo rand();?>" width="100px;height:100px;" onclick="this.src=‘code.php?+ Math.random()‘"> //點擊‘點擊切換’,切換驗證碼(需求二) <img id="captCode" src="./code.php?=--><?php //echo rand();?><!--" width="100px;height:100px;" > <a href="javascript:void(0)" onclick="document.getElementById(‘captCode‘).src=‘code.php?=<?php echo rand();?>‘">點擊切換?</a> </p> <p>請輸入驗證碼的內容: <input type="text" name="authcode" value=""/> </p> <P> <input type="submit" value="提交" style="padding:6px 20px;"/> </P> </form></body>
使用php如何產生驗證碼