這篇文章主要介紹了PHP通過GD庫實現驗證碼功能,結合實例形式分析了php驗證碼相關圖片繪製、輸出操作實現技巧,需要的朋友可以參考下
本文實例講述了PHP通過GD庫實現驗證碼功能。分享給大家供大家參考,具體如下:
首先看看實現的效果:
具體實現:
<?php /*PHP實現驗證碼*/ session_start();//開啓會話 //創建畫布 $image=imagecreatetruecolor(100,38); //背景顏色 $bgcolor=imagecolorallocate($image,255,255,255); imagefill($image,0,0,$bgcolor); $captch_code='';//存儲驗證碼 //隨機選取4個數字 for($i=0;$i<4;$i++){ $fontsize=10; // $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//隨機顏色 $fontcontent=rand(0,9); $captch_code.=$fontcontent; $x=($i*100/4)+rand(5,10); //隨機座標 $y=rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } /*//字母和數字混合驗證碼 for($i=0;$i<4;$i++) { $fontsize = 10; // $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));//?????? $data = 'abcdefghijklmnopqrstuvwxyz1234567890'; //數據字典 $fontcontent = substr($data, rand(0, strlen($data)), 1); $captch_code.=$fontcontent; $x = ($i * 100 / 4) + rand(5, 10); $y = rand(5, 10); imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); }*/ $_SESSION['code']=$captch_code; //增加干擾點 for($i=0;$i<200;$i++){ $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200)); imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);// } //增加干擾線 for($i=0;$i<3;$i++){ $linecolor=imagecolorallocate($image,rand(80,280),rand(80,220),rand(80,220)); imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor); } //輸出格式 header('content-type:image.png'); imagepng($image); //銷燬圖片 imagedestroy($image);
實現表單的連接和“換一個”功能的實現:
<input type="text" placeholder="驗證碼" name="verifycode" class="captcha"><br><br> <img id="captcha_img" src="captcha.php?r=<?php echo rand();?>" alt="驗證碼"> <label><a href="javascript:void(0)" rel="external nofollow" onclick="document.getElementById('captcha_img').src='captcha.php?r='+Math.random()">換一個</a> </label>
captcha.php後面加上一個隨機參數是爲了實現換一個驗證碼的功能,,換一個功能通過簡單的js即可實現。如果沒有這個功能可以不用參數。
更多關於PHP相關內容感興趣的讀者可查看本站專題:《PHP圖形與圖片操作技巧彙總》、《PHP數組(Array)操作技巧大全》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧彙總》
希望本文所述對大家PHP程序設計有所幫助。