利用php生成驗證碼
更新時間:2017年02月23日 08:50:13 作者:李宗禹
本文主要分享了利用php生成驗證碼的示例代碼,具有很好的參考價值,下面跟著小編一起來看下吧
話不多說,請看代碼:
<?php
/**
* php生成驗證碼
* @param $width 畫布寬
* @param $height 畫布高
* @param $vcodelen 驗證碼長度
* @param $pointnum 干擾像素點數(shù)量
* @param $linenum 干擾線條數(shù)量
*
* 思路:創(chuàng)建驗證碼畫布,生成并填充背景色,生成驗證碼內(nèi)容/干擾像素點/線,填充到畫布,輸出。
*/
$width = 100;
$height = 30;
$vcodelen = 4;
$pointnum = 200;
$linenum = 3;
// 創(chuàng)建畫布
$image = imagecreatetruecolor($width, $height);
// 創(chuàng)建色塊
$bgcolor = imagecolorallocate($image, 255, 255, 255);
// 填充畫布背景色
imagefill($image, 0, 0, $bgcolor);
// 驗證碼內(nèi)容
for ($i=0; $i < $vcodelen; $i++) {
// 字體大小
$fontsize = 5;
// 字體顏色,顏色在限定范圍內(nèi)隨機
$fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
$data = 'abcdefghijklmnopqrstuvwxyz0123456789';
// 驗證碼內(nèi)容在以上字符串內(nèi)隨機截取
$fontcontent = substr($data, rand(0,strlen($data)),1);
// 字符串顯示位置
$x = ($i*$width/4)+rand(5,15);
$y = rand(5,10);
// 字符串填充圖片
// imagestring的字體大小可選1-5,字體再大需要用imagettftext函數(shù)(需要字體文件)
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
// imagettftext($image, $fontsize, 0, $x, $y, $fontcolor, '/font/Geneva.dfont', $fontcontent);
}
// 干擾像素點
for ($i=0; $i < $pointnum; $i++) {
$pointcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
// 畫布填充像素點函數(shù)
imagesetpixel($image, rand(0,$width), rand(0,$height), $pointcolor);
}
// 干擾線條
for ($i=0; $i < $linenum; $i++) {
$linecolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
// 畫布填充線條函數(shù)
imageline($image, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $linecolor);
}
// 圖片輸出格式
header('content-type: image/png');
// 輸出驗證碼圖片
imagepng($image);
// 銷毀畫布
imagedestroy($image);
?>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
PHP error_log()將錯誤信息寫入一個文件(定義和用法)
PHP error_log()定義和用法,帶有二個簡單小例子加函數(shù)解釋2013-10-10
一個基于PDO的數(shù)據(jù)庫操作類(新) 一個PDO事務(wù)實例
原先已經(jīng)寫過一個PDO的數(shù)據(jù)庫操作類,這次只是在原先基礎(chǔ)上進行修改。2011-07-07
PHP 網(wǎng)絡(luò)開發(fā)詳解之遠程文件包含漏洞
由于PHP支持使用相同的函數(shù)(Function)對本地文件和遠程文件進行操作。因此,一些惡意用戶通過強行使網(wǎng)站上的PHP代碼(Code)包含自己的文件來實現(xiàn)執(zhí)行自己腳本的目的。2010-04-04
百度工程師講PHP函數(shù)的實現(xiàn)原理及性能分析(一)
這篇文章主要介紹了百度工程師講PHP函數(shù)的實現(xiàn)原理及性能分析(一),需要的朋友可以參考下2015-05-05

