验证码功能主要是为了防止网站登录功能被刷,但是根据现在市面上常见的验证码功能,很容易被绕过,所以如果想让网站足够安全的话,最好再研究深入一些
本章特针对留言板后台,增加验证码功能
一、首先需要在控制器中加入验证码方法admin/Lib/Action/LoginAction.class.php
知识点:
1、ob_clean函数用途
2、import方法调用think默认类库
3、Image类buildImageVerify方法使用
代码如下:
1
2
3
4
5
6
7
8
|
;
html
-
script
:
false
]
Public
function
verify
(
)
{
ob_clean
(
)
;
//ob_clean函数 清空先前输出,参考http://www.netingcn.com/php-ob_clean.html
import
(
'ORG.Util.Image'
)
;
//import调用的是message/ThinkPHP框架目录下的扩展包Extend/Library/ORG/Util/中的Image.class.php类文件
Image
::
buildImageVerify
(
)
;
//调用buildImageVerify方法生成验证码,默认参数为($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify'),有兴趣的朋友可以研究下Image类
}
|
二、在模板文件中加入验证码模块admin/Tpl/Login/index.html
知识点:
1、验证码图片调用
2、js相关运行流程了解
3、__PUBLIC__常量
在密码输入框后加入如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
;
html
-
script
:
false
]
<
!
DOCTYPE
html
PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"
>
<
html
>
<
head
>
<
meta
http
-
equiv
=
"Content-Type"
content
=
"text/html; charset=UTF-8"
>
<script
type
=
"text/javascript"
src
=
"__PUBLIC__/Js/jquery-1.7.2.min.js"
>
</script>
//__PUBLIC__常量可以在页面加载后,“查看页面源文件”中找到定义的__PUBLIC__目录,默认为项目根目录message下的Public目录,下面会讲解如何自定义__PUBLIC__系统常量
//jquery文件,只有加载了这个文件才可以调用jquery的方法,文件可在网上搜索下载http://download.csdn.net/download/renfengkai/4660552
<script
type
=
"text/javascript"
src
=
"__PUBLIC__/Js/login.js"
>
</script>
//这里的具体代码会在下面贴出,其实只是定义了一个change_code函数,也就是更换验证码的异步操作(可以在不刷新页面的情况下更换)
<
title
>
Message
Board
BackGround
<
/
title
>
<
/
head
>
<
body
>
<
form
action
=
"{:U('admin.php/Login/login')}"
method
=
"post"
name
=
"back_login"
>
<
h2
>简易后台登录系统
<
/
h2
>
用户名:
<
input
type
=
'username'
name
=
'username'
id
=
'username'
/
>
<
br
/
>
密码:
<
input
type
=
'password'
name
=
'password'
id
=
'password'
/
>
<
br
/
>
验证码:
<
input
type
=
"code"
name
=
"code"
/
>
//这里需要注意将type设置为code,name命名为code
<
img
src
=
"{:U('Admin/Login/verify','','')}"
id
=
"code"
/
>
//img标签下的src就是调用Login控制器中的veryfy方法
//后面的两个参数留空是必须的,其中第2个没实际意义,主要是为了第3个参数留空,这样设置可以取消伪静态后缀名,否则默认的伪静态后缀名为html,将会导致无法正常加载图片
<
a
href
=
"javascript:void(change_code(this));"
>看不清
<
/
a
>
//这里调用了个
<
br
/
>
<
input
type
=
"submit"
value
=
"登录"
/
>
<
/
form
>
<
/
body
>
<
/
html
>
|
login.js文件在message/Public/目录下
文件内容如下:
1
2
3
4
5
6
7
|
;
html
-
script
:
false
]
verifyURL
=
'http://localhost/message/admin.php/Login/verify'
;
//定义验证码路径
function
change_code
(
obj
)
{
$
(
"#code"
)
.
attr
(
"src"
,
verifyURL
+
'/'
+
Math
.
random
(
)
)
;
//动态生成验证码方法,有兴趣的朋友可以深入研究下jq方法
return
false
;
}
|
另:__PUBLIC__文件定义在message/admin/Conf/config.php
在配置中,加入如下内容,即可改变__PUBLIC__路径
配置如下:
1
2
3
4
5
|
;
html
-
script
:
false
]
//常量相关配置
'TMPL_PARSE_STRING'
=
>
array
(
'__PUBLIC__'
=
>
__ROOT_
_
.
'/'
.
APP
_NAME
.
'/Public'
,
//路径改变为message/admin/Public,刷新页面,验证码依然可以刷新,则表明js生效,也可“查看页面源文件”
)
,
|
收 藏
转载请注明:成长的对话 » (三)ThinkPHP实践之验证码讲解-TTLSA