實習就是做個留言本,留言需要驗證碼。
PHP驗證碼的實現,其實就是首先隨機數,然後繪圖。
關鍵的代碼為validcode.php中的:
<?php header("Content-Type:image/png");//開啟sessionsession_start();//隨機4個數字$code = "";$arr = array();for($i=0;$i<4;$i++){$arr[$i] = rand(0,9);$code .= (string)$arr[$i];}//設定入session中,方便比對$_SESSION["validcode"] = $code;//開始繪圖$width = 100;$height = 25;$img = imagecreatetruecolor($width,$height);//填充背景色$backcolor = imagecolorallocate($img,0,0,0);imagefill($img,0,0,$backcolor);//擷取隨機較深顏色 for($i=0;$i<4;$i++){$textcolor = imagecolorallocate($img,rand(50,180),rand(50,180),rand(50,180)); imagechar($img,12,7+$i*25,3,(string)$arr[$i],$textcolor);}//顯示圖片imagepng($img);//銷毀圖片imagedestroy($img);?>
然後再用一個頁面,放置img標籤,引入驗證碼。再用一個a標籤,供使用者切換驗證碼,防止看不清的情況。
<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><title>測試頁面</title><style type="text/css">a{font-size:12px;text-decoration:none;color:red;}a:hover{color:orange;}</style></head><body><img src="validcode.php" style="width:100px;height:25px;" id="code"/><a href="javascript:changeCode()">看不清,換一張</a></body></html><script type="text/javascript">function changeCode(){document.getElementById("code").src = "validcode.php?id="+Math.random();}</script>