php生成動態的驗證碼,是php防止惡意登陸或者注冊等常規手段-廢話不多說,直接看例子。(只是一個簡單的應用,如果要安全或者更復雜的,請期待我以后的文章)
PHP生成驗證碼核心文件 (checks.php):


<?php/*成生隨機的驗證碼。此實例只是一個簡單的例子,如果不想被人識別,還可以加噪點等干擾技術*/session_start(); //啟動sessionheader("Content-type:image/x-png"); //設置創建圖像的格式$image_width = 70; //設置圖像的寬度$image_height = 18; //設置圖像的高度srand(microtime()*100000); //設置隨機數的種子。 --這里關于srand和microtime函數請自行查閱php手冊for($i=0; $i<4; $i++) //循環輸出一個4位數的隨機數 {$new_number.=dechex(rand(0,15)); //將十進制隨機數轉為十六進制 }/*將獲取的隨機數驗證碼寫入到Session變量中 --這里注意php的變量作用范圍,和別的高級語言可能有些不同,所以要理解,自己去查手冊*/$_SESSION['check_checks'] = $new_number;$num_image = imagecreate($image_width,$image_height); //創建一個畫布imagecolorallocate($num_image,255,255,255); //設置畫布的顏色for($i=0; $i<strlen($_SESSION['check_checks']); $i++) //循環讀取session變量中的驗證碼 {$font = mt_rand(3,5); //設置隨機的字體大小$x = mt_rand(1,8)+$image_width*$i/4; //設置隨機字符所在的位置的X坐標$y = mt_rand(1,$image_height/4); //設置隨機字符所在的位置的Y坐標//設置字符的顏色$color = imagecolorallocate($num_image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));//水平畫出一行字符串 --輸出字符,此函數自行查閱php手冊。要GD2庫支持imagestring($num_image,$font,$x,$y,$_SESSION['check_checks'][$i],$color);}imagepng($num_image); //生成png格式的圖像imagedestroy($num_image); //結束圖像,釋放資源 ?>
PHP頁面驗證文件,判斷是否和生成的驗證碼相同 (login.php):


<?phpheader("Content-type:text/html;charset=utf-8");session_start(); //初始化sessionif($_POST['checks'] != "") //判斷是否請求過來的為空 {//如果不為空進行一個正則的替換,替換掉所有的空格 preg_replace()函數中用''而不是""來表示$checks = preg_replace('/[\s| ]/','',$_POST['checks']);echo "<script type='text/javascript'>prompt('這是您輸入的驗證碼:','$checks');</script>";if($checks == ""){echo "<script type='text/javascript'>alert('驗證碼不能為空');window.location.href='index.php';</script>"; }//如果用戶輸入驗證碼的值與隨機生成的驗證碼的值相等,則彈出登錄成功提示if($checks == $_SESSION['check_checks']){echo "<script type='text/javascript'>alert('用戶登錄成功');window.location.href='index.php';</script>"; }else{echo "<script type='text/javascript'>alert('您輸入的驗證碼不正確!');window.location.href='index.php';</script>"; }}else{echo "<script type='text/javascript'>alert('您沒有輸入驗證碼!');window.location.href='index.php';</script>"; } ?>
頁面呈現登陸文件 (index.html或者index.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" /> <title>無標題文檔</title> <script type="text/javascript">//封裝javascript的trim去掉字符串空格功能。function trim(strToTrim){//用正則來返回替換后的字符。--功能,去掉所有的空格!包括換行符等。 關于正則知識,請自行查閱資料return strToTrim.replace(/(\s+)/g,"");}function yz(){//先用js檢測是否已經輸入驗證碼,減少服務器壓力,當然服務器那邊也是要驗證的if(trim(form1.checks.value) == ""){alert("對不起!你沒有輸入驗證碼!");return false; //返回flase不提交 }return true;} </script> </head><body><div id="main"><form action="login.php" method="post" name="form1"><label>驗證碼:</label><input type="text" name="checks" /><img src="checks.php" title="驗證碼" alt="驗證碼顯示錯誤" /><br /><input type="submit" value="提交驗證" onclick="return yz();" /></form></div> </body> </html>
?