php利用驗證碼防止惡意注冊學習筆記
來源:程序員人生 發布時間:2014-01-03 15:04:57 閱讀次數:3078次
常用的防止惡意注冊就是利用驗證碼來實現了,在用戶提交注冊信息時我隨機生成一個圖形驗證碼,這樣只有人能識別了,當然簡單的驗證碼機器是機以識別的,所以復雜點的好。
今天我們來研究下PHP驗證碼,我們通過簡單的數字驗證碼來實現,首先來寫一個生成驗證碼的代碼:
- <?php
-
- $num=”"; for($i=0;$i<4;$i++){ $num .= rand(0,9); }
-
-
- Session_start(); $_SESSION["Checknum"] = $num;
-
- srand((double)microtime()*1000000);
- $im = imagecreate(60,20);
- $black = ImageColorAllocate($im, 0,0,0);
- $gray = ImageColorAllocate($im, 200,200,200);
- imagefill($im,0,0,$gray);
-
- $style = array($black, $black, $black, $black, $black, $gray, $gray, $gray, $gray, $gray);
- imagesetstyle($im, $style);
- $y1=rand(0,20); $y2=rand(0,20); $y3=rand(0,20); $y4=rand(0,20);
- imageline($im, 0, $y1, 60, $y3, IMG_COLOR_STYLED);
- imageline($im, 0, $y2, 60, $y4, IMG_COLOR_STYLED)
-
- for($i=0;$i<80;$i++) {
- imagesetpixel($im, rand(0,60), rand(0,20), $black); }
-
- $strx=rand(3,8);
- for($i=0;$i<4;$i++){
- $strpos=rand(1,6); imagestring($im,5,$strx,$strpos, substr($num,$i,1), $black); $strx+=rand(8,12);
- }
- ImagePNG($im); ImageDestroy($im);
- ?>
在reg.php頁面我們寫一個表單:(此處省去了其他的HTML代碼),代碼如下:
- <tr>
- <td>驗證碼 :</td>
- <td><input type=”text” name=”yzm”style=”width:60px;height:20px;” /><img src=”code.php” onclick=”javascript:this.src=’code.php?’+Math.random();”></img></td>
- </tr>
- <tr> <td colspan=’2′><input type=”submit” value=”注冊”/></td>
- <td>驗證碼 :</td>
- </tr>
因為我們是用post提交的,所以我們用$_POST來獲取(在接受頁面做驗證碼的驗證:post.php頁面)代碼如下:
- Session_start();
-
- function back_alert($yzm){
- echo “<script type=’text/javascript’>alert(‘$yzm’);history.back();</script>”;
- }
-
- if($_POST["yzm"]==null){
- back_alert(‘你都木有輸入驗證碼,有木有???’); }
-
- if(!($_POST["yzm"]==$_SESSION["Checknum"])){
- back_alert(‘驗證碼不正確’);
- } echo $_POST["yzm"];
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈