PHP驗證碼的實現____PHP

來源:互聯網
上載者:User

實習就是做個留言本,留言需要驗證碼。

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>


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.