php怎么添加验证码,PHP添加验证码以及使用
現在很多頁面在使用表單提交時,都會使用到驗證碼的使用、如何制做一個驗證碼呢?這里有一個用PHP的方法 以及代碼
1、首先在php.ini 配置文件里面把GD庫打開? // 在php.ini里面找到 extension=php_gd2.dll 把前面的分號刪去。
2、代碼:<?php
session_start();
//用php的header方法表名輸出內容的格式為png
//?輸出圖片前,必須提前輸出header信息
//imagecreatetruecolor默認輸出是黑色的背景
header('content-type:image/png');
//1.通過imagecreatetruecolor?創建一個驗證碼所需要的底圖
$image?=?imagecreatetruecolor(100,30);
//2.用imagecolorallocate?填充背景
$bgcolor?=?imagecolorallocate($image,000,255,255);
//3、填充到我們的底圖當中
imagefill($image,0,0,$bgcolor);
//定義一個空字符串?來用存儲驗證碼
$captchCode?=?'';
//for循環來輸出驗證碼位數
for?($i=0;?$i?
//字體大小為6
$fontSize?=?6;
//設置背景字體
$fontColor?=?imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));
$data?=?'abcdefghijklmnopqrstuvwxyz0123456789';
//隨機從data?中取出一個字符
$fontContent?=?substr($data,rand(0,strlen($data)),1);
//將取出的一位字符存儲到captchCode當中;
$captchCode?.=?$fontContent;
$x?=?($i?*?100/4)+rand(5,10);
$y?=?rand(5,10);
imagestring($image,$fontSize,$x,$y,$fontContent,$fontColor);
}
//將生成好的驗證碼保存進session
$_SESSION['code']?=?$captchCode;
//循環出200個點
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);
}
//創建8條橫線
for($i=0;$i<3;$i++){
$linecolor?=?imagecolorallocate($image,rand(60,220),rand(60,220),rand(60,220));
imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
//返回圖片
imagepng($image);
//銷毀
imagedestroy($image);
?>
3、在表單input 添加個點擊事件 ?οnclick="this.src = this.src+'?'+ Math.random(0,999)? 即點擊后刷新驗證碼
總結
以上是生活随笔為你收集整理的php怎么添加验证码,PHP添加验证码以及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 子查询 as_mysql子查
- 下一篇: 动态规划算法php,php算法学习之动态