1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 1. 先建立captcha.php,用於產生我們所需要的驗證碼圖片。 captcha.php: <?php session_start(); Header("Content-type: image/PNG"); //在session中自訂使用capstr這個變數來儲存產生的字串 $_SESSION['capstr']=""; //產生一個90*30的圖檔 $im = imagecreate(90,30) or die("Cant's initialize new GD image stream!"); //定義使用的顏色,wordColor為字體顏色,bgColor為底色,noiseColor為黑點雜訊 //若要更動,請自行更改後面三個整數,依序為R、G、B範圍皆在0~255間 $wordColor = ImageColorAllocate($im, 255, 255, 255); $bgColor = ImageColorAllocate($im, 112, 128, 144); $noiseColor = ImageColorAllocate($im, 211, 211, 211); //將圖片底色填色 imagefill($im, 0, 0, $bgColor); //定義候選的字母,剔除掉一些會混淆的,如大寫I與L $ychar="A,B,C,E,F,H,K,L,M,N,P,R,T,U,V,W,X,Y,Z"; $list=explode(",",$ychar); $cnt = count($list)-1; //亂數挑選四個字母,字母可重複 for($i=0;$i<4;$i++){ $randnum=rand(0,$cnt); $authnum.=$list[$randnum]." "; } //將最後挑選出來的結果存入session $_SESSION['capstr']=str_replace(" ","",$authnum); //將挑選出來的字串印在圖片上,這邊你必須自備truetype的英文字型檔 //注意字形檔的路徑 putenv('GDFONTPATH=' . realpath('.')); imagettftext($im, 12, 3, 8, 24, $wordColor, "tatu_font.ttf", $authnum); //加入200個黑點雜訊 for($i=0;$i<200;$i++) imagesetpixel($im, rand()%90 , rand()%30 , $noiseColor); //最後將圖片產生並且印出來 ImagePNG($im); ImageDestroy($im); ?> 2. 建立test.php,用於輸入驗證碼。 test.php: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="utf-8" /> <title>test</title> <script type='text/javascript'> </script> </head> <body style="text-align:center;"> <form method="post" name="testForm" action="test1.php" enctype="multipart/form-data"> <img src="captcha.php" border="0" alt="" width="90" height="30" /> 請輸入上面的驗證碼(皆為大寫英文字母): <input id="captcha" name="captcha" type="text" /> <input type="submit" name="submit" value=" 登 入 " /> </form> </body> </html> 3. 建立test1.php,用於接收驗證碼。 test1.php: <?php session_start(); $code = strtoupper($_POST['captcha']); if($code == "" || $code != $_SESSION['capstr'] || strlen($code) != 4) { //開始寫輸入錯誤的處理,這邊舉例是導到yahoo!kimo header("Location: http://www.yahoo.com.tw/"); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="utf-8" /> <title>test1</title> <script type='text/javascript'> </script> </head> <body style="text-align:center;"> 恭喜 </body> </html> |
Direct link: https://paste.plurk.com/show/5041