php 创建汉字验证码
在该脚本的所有需要,我们会计算生成图表变量第一的第二部分。然后,我们准备的
主要形象,实际输出数据。每个类型的结果是一个从数据库教程中挑选一个,得票率计算
,然后酒吧和解释性说明的输出。
在此脚本中,我们使用的是TrueType字体获得反锯齿文本。功能与TrueType字体的工
作有自己的特点。首先,你需要的字体点所在。为此,系统变量GDFONTPATH设置。然
后,我们需要设置字体的名称。 TrueType字体渲染使用ImageTTFText()。
我们已经讨论了上面的绘图中使用的所有功能,代码有意见,是很清楚的,所以你不
应该有任何麻烦。
//Tell gd2, where your fonts reside
putenv('GDFONTPATH=C:WINDOWSFonts');
$font = 'arial';
//Set starting point for drawing
$y = 50;
//Specify constant values
$width = 700; //Image width in pixels
$bar_height = 20; //Bars height
$height = $num_poller * $bar_height * 1.5 + 70; //Calculating image height
$bar_unit = ($width - 400) / 100; //Distance on the bar chart standing for
1 unit
//Create the image resource
$image = ImageCreate($width, $height);
//We are making four colors, white, black, blue and red
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$red = ImageColorAllocate($image, 255, 0, 0);
$blue = imagecolorallocate($image,0,0,255);
//Create image background
ImageFill($image,$width,$height,$white);
//Draw background shape
ImageRectangle($image, 0, 0, $width-1, $height-1, $black);
//Output header
ImageTTFText($image, 16, 0, $width/3 + 50, $y - 20, $black, $font, 'Poll
Results');
while ($row = mysql教程_fetch_object($result)) {
if ($total_votes > 0)
$percent = intval(round(($row->num_votes/$total_votes)*100));
else
$percent = 0;
//Output header for a particular value
ImageTTFText($image,12,0,10, $y+($bar_height/2), $black, $font, $row-
>book_type);
//Output percentage for a particular value
ImageTTFText($image, 12, 0, 170, $y +
($bar_height/2),$red,$font,$percent.'%');
$bar_length = $percent * $bar_unit;
//Draw a shape that corresponds to 100%
ImageRectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)),
$y+$bar_height, $black);
//Output a bar for a particular value
ImageFilledRectangle($image,220,$y-2,220+$bar_length, $y+$bar_height,
$blue);
//Output the number of votes
ImageTTFText($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black,
$font, $row->num_votes.' votes cast.');
//Going down to the next bar
$y = $y + ($bar_height * 1.5);
}
//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");
//Output the newly created image in jpeg format
ImageJpeg($image);
//Free up resources
ImageDestroy($image);
?>
<?php
002 class Captcha
003 {
004 private $_about = array(
005 'imageLine'=>8, // 线条干扰,为0正常
006 'imagePixel'=>300, // 像素干扰,为0正常
007 'location'=>true, // 字体随机位置,false正常
008 'bgColor'=>'#ffffff', // 背景
009 'textColor'=>'', // 文本
010 'borColor'=>'#e1e1e1', // 边框
011 'lineColor'=>'#dedede', // 线条
012 'pixelColor'=>'#646464' // 像素
013 );
014
015 /**
016 * 构造<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=%BA%AF%CA%FD">函数</SPAN>
017 */
018 public function __construct(){}
019
020 /**
021 * setCookie
022 *
023 * @param string $data 写入<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=%CA%FD%BE%DD">数据</SPAN>
024 */
025 public function setCookie($data)
026 {
027 if (is_array($data)) {
028 $string = '';
029 foreach ($data as $v) $string .= $v;
030 $data = $string;
031 }
032 setcookie('captcha',$data,time()+60,'/');
033 }
034 /**
035 * setCaptcha
036 *
037 * 设置输出<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=%D1%E9%D6%A4">验证</SPAN>码
038 *
039 * @param integer $width 宽
040 * @param integer $height 高
041 * @param integer $fontSize 字体大小
042 * @param string $font 字体<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=%CE%C4%BC%FE">文件</SPAN>位置
043 * @param integer $length 验证<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=%D7%D6%B7%FB">字符</SPAN>长度
044 * @param integer $type 验证字符类型
045 * 1:只数字,2:只小写字母,3:只大写字母,
046 * 4:小写字母数字混合,5:大写字母数字混合,6:大小写字母数字混合,7:汉字
047 * @param array $about 验证码配置
048 */
049 public function setCaptcha($width=80,$height=30,$fontSize=13,$font='code.ttf',$length=4,$type=3,$about=array())
050 {
051 is_array($about) || exit('参数出错!');
052 foreach ($about as $key=>$value) {
053 if (array_key_exists($key,$this->_about)) {
054 $this->_about[$key] = $value;
055 }
056 }
057
058 extract($this->_about,EXTR_OVERWRITE);
059 $im = imagecreatetruecolor($width,$height);
060 // 背景颜色
061 $bgC_Arr = $this->getColor($bgColor);
062 $imgBgColor = imagecolorallocate($im,$bgC_Arr[0],$bgC_Arr[1],$bgC_Arr[2]);
063 // 边框颜色
064 $borC_Arr = $this->getColor($borColor);
065 $imgBorderColor = imagecolorallocate($im,$borC_Arr[0],$borC_Arr[1],$borC_Arr[2]);
066 // 填充
067 imagefill($im,0,0,$imgBgColor);
068 imagerectangle($im,0,0,$width-1,$height-1,$imgBorderColor);
069
070 // 画线
071 if ($imageLine) {
072 // 线条颜色
073 $lineC_Arr = $this->getColor($lineColor);
074 $imgLineColor = imagecolorallocate($im,$lineC_Arr[0],$lineC_Arr[1],$lineC_Arr[2]);
075 for ($i=0;$i<$imageLine;$i++) {
076 imageline($im,0,mt_rand(0,$height),$width,mt_rand(0,$height),$imgLineColor);
077 }
078 }
079 // 像素干扰
080 if ($imagePixel) {
081 // 像素颜色
082 $pixelC_Arr = $this->getColor($pixelColor);
083 $imgPixelColor = imagecolorallocate($im,$pixelC_Arr[0],$pixelC_Arr[1],$pixelC_Arr[2]);
084 for ($i=0;$i<$imagePixel;$i++) {
085 imagesetpixel($im,mt_rand(2,$width-2),mt_rand(2,$height-2),$imgPixelColor);
086 }
087 }
088
089 // 获取字串
090 if (!$text = $this->getText($type,$length)) exit('验证码没有查找到指定字符类型!');
091 // 检查字体文件
092 is_file($font) || exit('验证码未查找到指定字体文件!');
093 $y = ceil($height / 2)+ceil($fontSize/2)*0.9;
094 $pitch = ceil($width / $length);
095 $text = ctype_alnum($text)?$text:str_split($text,3);
096 $pad = 0;
097 for ($i=0;$i<$length;$i++) {
098 if (!empty($textColor)) {
099 // 文本颜色
100 $txtC_Arr = $this->getColor($textColor);
101 $imgTextColor = imagecolorallocate($im,$txtC_Arr[0],$txtC_Arr[1],$txtC_Arr[2]);
102 } else {
103 $imgTextColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
104 }
105 if (false === $location) {
106 $fontSizePad = ctype_alnum($text[$i]) ? $fontSize*1.4 : $fontSize*1.7;
107 $x = $pad + $fontSize + (ceil($pitch/2) - $fontSizePad);
108 imagettftext($im,$fontSize,0,$x,$y,$imgTextColor,$font,$text[$i]);
109 $pad += $pitch;
110 } else {
111 $d = $pad += $pitch;
112 $d += $fontSize*0.5;
113 imagettftext($im,$fontSize,mt_rand(-20,20),mt_rand($d-=$pitch,$pad-$fontSize*1.4),$y,$imgTextColor,$font,$text[$i]);
114 }
115 }
116 // 写入<SPAN class=t_tag onclick=tagshow(event) href="tag.php?name=session">session</SPAN>
117 $this->setCookie($text);
118 $this->getCaptcha($im);
119 }
120
121 /**
122 * getText
123 *
124 * 获取字符串
125 *
126 * @param integer $type 字串类型
127 * @param integer $length 长度
128 * @return string $result 字串结果
129 */
130 public function getText($type,$length)
131 {
132 $result = '';
133 $range = array();
134 switch ($type) {
135 case 1 :
136 for ($i=0;$i<$length;$i++) $result .= mt_rand(0,9);
137 break;
138 case 2 :
139 $range = range('a','z');
140 break;
141 case 3 :
142 $range = range('A','Z');
143 break;
144 case 4 :
145 $range = array_merge(range(0,9),range('a','z'));
146 break;
147 case 5 :
148 $range = array_merge(range(0,9),range('A','Z'));
149 break;
150 case 6 :
151 $range = array_merge(range(0,9),range('a','z'),range('A','Z'));
152 break;
153 case 7 :
154 // for ($i=0;$i<$length;$i++) $result .= iconv('gb2312','utf-8',chr(rand(0xB0,0xF7)).chr(rand(0xA1,0xFE)));
155 $range = array(
156 '佟','爱','菲','可','天','一','新','他','策','韵','年','明','礼','杰','雅','诗','忍','子',
157 '好','快','乐','半','美','拜','亮','臣','香','中','国','开','心','阿','笑','图','成','虎'
158 );
159 break;
160 default : return false;
161 }
162 if (!empty($range)) {
163 shuffle($range);
164 $result = mb_substr(implode('',$range),0,$length,'utf-8');
165 }
166 return $result;
167 }
168
169 /**
170 * getColor
171 *
172 * 十六进制颜色转为十进制
173 */
174 public function getColor($string)
175 {
176 $string = str_replace('#','',$string);
177 if (!ctype_alnum($string)) {
178 return false;
179 }
180 $rgb_Arr = array();
181 if (strlen($string) == 3) {
182 for ($i=0;$i<3;$i++) {
183 $rgb_Arr[$i] = hexdec(str_repeat($string{$i},'2'));
184 }
185 } else if (strlen($string) == 6) {
186 $colorSp = str_split($string,2);
187 foreach ($colorSp as $v) {
188 $rgb_Arr[] = hexdec($v);
189 }
190 } else {
191 return false;
192 }
193 return $rgb_Arr;
194 }
195
196 public function getCaptcha($im)
197 {
198 header('Content-type: image/gif');
199 imagegif($im);
200 imagedestroy($im);
201 }
202 }
203
204 $about = array(
205 'imageLine'=>0, // 线条干扰,为0正常
206 'imagePixel'=>300, // 像素干扰,为0正常
207 'location'=>false, // 字体随机位置,false正常
208 'bgColor'=>'#ffffff', // 背景颜色
209 'textColor'=>'', // 文本颜色,默认随机颜色
210 'borColor'=>'#e1e1e1', // 边框颜色
211 'lineColor'=>'#ff0000', // 线条颜色
212 'pixelColor'=>'#a13e3e' // 像素颜色
213 );
214 error_reporting(0);
215 $a = new Captcha();
216 $a->setCaptcha(100,30,13,'font.ttf',4,1,$about);
起初,有一个在php.ini 看看gd库是不是开启的,
下一步,我们会考虑每一个细节的图像生成步骤。
<?php
//Send a generated image to the browser
create_image();
exit();
function create_image()
{
//Let's generate a totally random string using md5
$md5 = md5(rand(0,999));
//We don't need a 32 character long string so we trim it down to 5
$pass = substr($md5, 10, 5);
//Set the image width and height
$width = 100;
$height = 20;
//Create the image resource
$image = ImageCreate($width, $height);
//We are making three colors, white, black and gray
$white = ImageColorAllocate($image, 255, 255, 255);
$black = ImageColorAllocate($image, 0, 0, 0);
$grey = ImageColorAllocate($image, 204, 204, 204);
//Make the background black
ImageFill($image, 0, 0, $black);
//Add randomly generated string in white to the image
ImageString($image, 3, 30, 3, $pass, $white);
//Throw in some lines to make it a little bit harder for any bots to
break
ImageRectangle($image,0,0,$width-1,$height-1,$grey);
imageline($image, 0, $height/2, $width, $height/2, $grey);
imageline($image, $width/2, 0, $width/2, $height, $grey);
//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");
//Output the newly created image in jpeg format
ImageJpeg($image);
//Free up resources
ImageDestroy($image);
}
?>
验证码调用方法
<img height="120" alt="Dynamically generated image"
src="generate_image.php" width="200">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>php 文件上传只允许上传图像文件</title>
</head>
<body>
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="">
<label>
<input type="file" name="file" />
</label>
<label>
<input type="submit" name="Submit" value="提交" />
</label>
</form>
</body>
</html>
<?php
if($_FILES){
foreach( $_FILES as $key => $_value )
{
$_FILES[$key]['type'] =$_value['type'];
}
if(substr($_FILES[$key]['type'],0,6) !='image/')
{
exit;
}
}
echo '<hr/>';
print_r($_FILES);
echo '<hr/>';
echo var_export($_FILES);
?>
首先判断$_FILES['inputname']['type'],对于能够识别的类型更正文件后缀,然后再判断后缀。
因为$_FILES['inputname']['type']只能识别少数类型,但是它是根据文件内容来识别的,特别是对于许多把BMP图形保存为JPG文件的相机,一下就现原型了,而你的程序可能针对BMP有转换为JPG的处理。
<?php
function passport_encrypt($txt, $key) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}
function passport_decrypt($txt, $key) {
$txt = passport_key(base64_decode($txt), $key);
$tmp = '';
for($i = 0;$i < strlen($txt); $i++) {
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}
function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = '';
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
?>
以下是一些示例…加深对这三个加密解密函数的理解…
//string.php
<?php
include “fun.php”;
$txt = “This is a test”;
$key = “testkey”;
$encrypt = passport_encrypt($txt,$key);
$decrypt = passport_decrypt($encrypt,$key);
echo $txt.”<br><hr>”;
echo $encrypt.”<br><hr>”;
echo $decrypt.”<br><hr>”;
?>
//array.php
<?php
include “fun.php”;
$array = array(
"a" => "1",
"b" => "2",
"c" => "3",
"d" => "4"
);
//serialize产生一个可存储的值,返回一个字符串,unserialize还原
$txt = serialize($array);
$key = “testkey”;
$encrypt = passport_encrypt($txt,$key);
$decrypt = passport_decrypt($encrypt,$key);
$decryptArray = unserialize($decrypt);
echo $txt.”<br><hr>”;
echo $encrypt.”<br><hr>”;
echo $decrypt.”<br><hr>”;
echo $decryptArray.”<br><hr>”;
?>
关键的地方来了…当你要跳转到另外一个网址,但又要保证你的session无误的时候,你需要对session作一个处理.貌似一个公司有一个网站又有一个论坛,两个地方都有注册和登录,但又不想让用户在主页登录后跳转到论坛的时候session失效,即是登录一次跑完整间公司…
那要怎样来处理用户的session呢…
网页都是无状态的,如果要在新的网页中继续使用session,则需要把session从一个地方移到另一个地方,可能有些人已经想到了,我可以通过url传址的方式来调用它….而PHP有个处理session的变量,叫$_SESSION.于是….
将需要注册的session转换成一个数组吧.那么,你可以这样写:
//login.php
<?php
session_start();
include “fun.php”;
….
$_SESSION[“userid”];
$_SESSION[“username”];
$_SESSION[“userpwd”];
…
header("Location: http://$domain/process.php?s=".urlencode(passport_encrypt(serialize($_SESSION),"sessionkey")));
?>
上例中先用serialize将$_SESSION变成可存储的数据,然后通过passport_encrypt将这个数据加密,加urlencode的原因是因为$_SESSION加密时,有可能会产生像料想不到的编码,所以以防万一…(事实证明非常有效)
处理下先
//process.php
<?php
session_start();
include “fun.php”;
$_SESSION=unserialize(passport_decrypt($_GET["s"],"sessionkey"));
header("Location: http://$domain/index.php");
?>
先用$_GET[“s”]获取URL的参数,然后用passport_decrypt将其解密,再用unserialize将其数据还原成原始数据
到了这步处理,你的网页就可能通过header自由跳转啦….
这种方法还涉及到安全性的问题,如果你的url地址在传址的过程中被人家获取的话,那就真的是不好意思了…人家虽然可能破解不了url里边的内容,但人家也可以直接用这个url地址来登录你的一些个人账户啊,邮箱帐户啊甚至银行帐户(当然很少人会这样写,我例外,哈哈)…听起来好怕….但其实你可以在跳转页面作取消session处理….
以下是加强版的process.php
<?php
session_start();
include_once "fun.php";
$_SESSION=unserialize(passport_decrypt($_GET["s"],"sessionkey"));
if((time()-$_SESSION["TIME"])>30){
header("Location: http://$domain/ login.php");
unset($_SESSION["USERNAME"]);
unset($_SESSION["PASSWORD"]);
}
else
header("Location: http://$domain/ index.php");
?>
写这个文件之前,你还要在登录那边设置
$_SESSION["TIME"] = time();
设置这个的原因主要是获取两边的时间,如果跳转的时候超过30秒的时候,你就可以让它跳转到login.php登录页面,网速慢的客户就不好意思啦…但这也预防了如果此url被人获取,而这个人又没有在30秒内登录的话,那就不好意思啊,超时重新登录.
$_SESSION["USERNAME"]和$_SESSION["PASSWORD"] 这两个东东就是用户登录时需要输入的用户名和密码了….取消这两个session的原因就是因为如果你的url被人获取了,那个人虽然在超过30秒内跳转到loign.php的页面,但那些传过来的session依然有效,只要将url后缀login.php改为index.php….那他一样登录成功…
相关文章
- 最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04
jQuery Real Person验证码插件防止表单自动提交
本文介绍的jQuery插件有点特殊,防自动提交表单的验证工具,就是我们经常用到的验证码工具,先给大家看看效果。效果图如下: 使用说明 需要使用jQuery库文件和Real Person库文件 同时需要自定义验证码显示的CSS样式 使用实例...2015-11-08- 这篇文章主要介绍了JS创建Tag标签的方法,结合具体实例形式分析了javascript动态操作页面HTML元素实现tag标签功能的步骤与相关操作技巧,需要的朋友可以参考下...2017-06-15
- 这篇文章主要为大家详细介绍了JS实现随机生成验证码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-06
- 1.创建div元素: Javascript代码 复制代码 代码如下: <scripttypescripttype="text/javascript"> functioncreateElement(){ varcreateDiv=document.createElement("div"); createDiv.innerHTML="Testcreateadiveleme...2013-10-13
- 通过jquery.cookie.js插件可以快速实现“点击获取验证码后60秒内禁止重新获取(防刷新)”的功能效果图:先到官网(http://plugins.jquery.com/cookie/)下载cookie插件,放到相应文件夹,代码如下:复制代码 代码如下: <!DOCTYPE ht...2015-03-15
- 验证码类文件 CreateImg.class.php <?php class ValidationCode { private $width,$height,$codenum; public $checkcode; //产生的验证码 private $checkimage; //验证码图片 private $disturbColor = ''; /...2015-11-08
- 这篇文章主要介绍了基于JavaScript实现验证码功能的相关资料...2017-04-03
- PS怎么创建变形文字?ps中想要给输入的文字变形,该怎么调整文字的显示形态呢?下面我们就来看看ps给文字变形的方法,需要的朋友可以参考下 我们在图层上输入文字后,可以...2017-07-06
- 什么是cookie? cookie 是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie。你可以使用 JavaScript 来创建和取回 cookie 的值。 有关cookie的例子: 名字 cookie 当访...2014-05-31
Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法
这篇文章主要介绍了Bootstrap中文本框的宽度变窄并且加入一副验证码图片的实现方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下...2016-06-24- 下面小编就为大家带来一篇单击按钮发送验证码,出现倒计时的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧 代码...2017-07-06
- 验证码是一个现在WEB2.0中常见的一个功能了,像注册、登录又或者是留言页面,都需要注册码来验证当前操作者的合法性,我们会看到有些网站没有验证码,但那是更高级的验证了,...2016-11-25
- 这篇文章主要介绍了基于Pytorch版yolov5的滑块验证码破解思路详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-25
- 下面小编就为大家带来一篇javascript创建对象的几种模式介绍。小编觉得挺不错的,现在分享给大家,也给大家做个参考...2016-05-09
- 最近接到新需求,需要实现一个点击发送验证码之后,按钮禁用,在5秒之后取消禁用,看似需求很简单,实现起来还真的好好动动脑筋,下面小编把jquery控制按钮禁用核心代码分享给大家,需要的朋友参考下吧...2021-07-24
idea 无法创建Scala class 选项的原因分析及解决办法汇总
这篇文章主要介绍了idea 无法创建Scala class 选项的解决办法汇总,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02- 工信部的ICP备案网站登录时验证码一直输入不正确怎么回事,为了防止一些机器采集人工信部对于查询验证做得识别度极低,所以许多的朋友都会发现输入验证码一直有问题了,那...2016-10-10
- 写递归函数,可考虑缓存,定义一些静态变量来存上一次运行的结果,多程序运行效率很有帮助.。 大概步骤如下: step1:到数据库取数据,放到一个数组, step2:把数据转化为一个树型状的数组, step3:把这个树型状的数组转为html代码。...2015-11-08
- 下面小编就为大家带来一篇.Net(c#)汉字和Unicode编码互相转换实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25