前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Typecho小试牛刀]Joe主题增加验证码(非插件方式)

[Typecho小试牛刀]Joe主题增加验证码(非插件方式)

原创
作者头像
TDP-苏苏
修改2022-05-17 16:52:02
1.1K0
修改2022-05-17 16:52:02
举报
文章被收录于专栏:上云实践笔记

刚刚接触Typecho,发现Joe主题不错,摸索了两天之后,发现Joe本身不支持评论验证码,就查阅资料,修改部分Joe主题文件,增加评论验证码。

当前版本

  • Typecho:1.2.0
  • Joe主题:7.3.6

目标

  • 非插件方式,简单实现评论验证码,防止机器人灌水。

涉及文件

/Joe/core/function.php (必须)

  • 目的: 增加需要用到的函数
  • 增加如下3个函数
代码语言:php
复制
#生成验证码
function comment_protection_code(){
    $num1=rand(1,9);
    $num2=rand(1,9);
    $rand=rand(1,100)%3;
    switch($rand){
        case 0:
            $ret=$num1 + $num2;
            $symbol='+';
        break;
        case 1:
            $ret=$num1 - $num2;
            $symbol='-';
        break;
        case 2:
            $ret=$num1 * $num2;
            $symbol='×';
        break;
    }
    $_SESSION['verify']=$ret;
    $_SESSION['verify_md5']=md5($num1.$num2);
    echo "<input type=\"text\" autocomplete=\"off\" name=\"sum\" placeholder=\"$num1 $symbol $num2 = ?\" />";
    echo "<input type=\"hidden\" name=\"num1\" value=\"$num1\">\n";
    echo "<input type=\"hidden\" name=\"num2\" value=\"$num2\">";
}
#验证
function comment_protection_do($comment, $post, $result){
    if(md5($_SESSION['verify']) != md5($_POST['sum']) || $_SESSION['verify_md5'] != md5($_POST['num1'].$_POST['num2'])){
        throw new Typecho_Widget_Exception(_t('对不起: 验证码错误,请重试。','评论失败'), 200);
    }
    return $comment;
}
#判断路由用到
function endsWith($haystack, $needle){
    return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}

/Joe/core/core.php (必须)

  • 目的: 挂载验证函数
  • 搜索函数 themeInit ,将如下代码粘贴到函数内
代码语言:php
复制
#仅在提交评论时生效
if(endsWith($self->request->getPathInfo(), '/comment')){
    $comment = comment_protection_do($comment, $post, $result);
}

/Joe/public/comment.php (必须)

  • 目的: 增加验证码输入框
  • 搜索 输入网址 ,在它的下方增加一个兄弟节点,用来输入验证码
代码语言:php
复制
...
<div class="list">
    <input type="text" autocomplete="off" name="url" placeholder="请输入网址(非必填)..." />
</div>
#上方为原始代码
#下方为新增
<!-- @苏苏修改 增加验证码输入框-->
<div class="list">
    <?php comment_protection_code();?>
</div>

/Joe/assets/js/joe.global.js (必须)

  • 目的: 在提交评论时,增加验证码校验参数
  • 打开未压缩版js文件,搜索激活评论提交,用下方代码替换,然后压缩后替换同文件夹的joe.global.min.js
代码语言:javascript
复制
       /* 激活评论提交 已修改 */
	{
		if ($('.joe_comment').length) {
			let isSubmit = false;
			$('.joe_comment__respond-form').on('submit', function (e) {
				e.preventDefault();
				const action = $('.joe_comment__respond-form').attr('action') + '?time=' + +new Date();
				const type = $('.joe_comment__respond-form').attr('data-type');
				const parent = $('.joe_comment__respond-form').attr('data-coid');
				const author = $(".joe_comment__respond-form .head input[name='author']").val();
				const _ = $(".joe_comment__respond-form input[name='_']").val();
				const mail = $(".joe_comment__respond-form .head input[name='mail']").val();
				const url = $(".joe_comment__respond-form .head input[name='url']").val();
				const sum = $(".joe_comment__respond-form .head input[name='sum']").val();
				const num1 = $(".joe_comment__respond-form .head input[name='num1']").val();
				const num2 = $(".joe_comment__respond-form .head input[name='num2']").val();
				let text = $(".joe_comment__respond-form .body textarea[name='text']").val();
				if (sum === '') return Qmsg.info('请输入验证信息!');
				if (author.trim() === '') return Qmsg.info('请输入昵称!');
				if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(mail)) return Qmsg.info('请输入正确的邮箱!');
				if (type === 'text' && text.trim() === '') return Qmsg.info('请输入评论内容!');
				if (type === 'draw') {
					const txt = $('#joe_comment_draw')[0].toDataURL('image/webp', 0.1);
					text = '{!{' + txt + '}!} ';
				}
				if (isSubmit) return;
				isSubmit = true;
				$('.joe_comment__respond-form .foot .submit button').html('发送中...');
				$.ajax({
					url: action,
					type: 'POST',
					data: { author, mail, text, parent, url, num1, num2, sum, _ },
					dataType: 'text',
					success(res) {
						let arr = [],
							str = '';
						arr = $(res).contents();
						Array.from(arr).forEach(_ =### {
							if (_.parentNode.className === 'container') str = _;
						});
						if (!/Joe/.test(res)) {
							Qmsg.warning(str.textContent.trim() || '');
							isSubmit = false;
							$('.joe_comment__respond-form .foot .submit button').html('发表评论');
						} else {
							window.location.reload();
						}
					},
					error(res) {
						isSubmit = false;
						$('.joe_comment__respond-form .foot .submit button').html('发表评论');
						Qmsg.warning('发送失败!请刷新重试!');
					}
				});
			});
		}
	}

自定义css(可选)

  • 目的: 在输入框左侧增加竖形分割线,统一外观
  • 添加方式:后台->Joe主题设置->全局设置->自定义CSS,增加如下样式
代码语言:css
复制
/*验证码处css*/
@media (min-width: 768px){.joe_comment__respond-form .head .list:nth-child(4){position:relative}.joe_comment__respond-form .head .list:nth-child(4)::before{content:'';position:absolute;top:50%;transform:translateY(-50%);width:1px;height:15px;background:var(--classA)}.joe_comment__respond-form .head .list:nth-child(4)::before{left:0}}

最终效果

验证码位置
验证码位置

未输入验证码提示

未输入验证码提示
未输入验证码提示

验证码错误提示

验证码错误提示
验证码错误提示

笔者为TDP成员,点击了解TDP详情

原文链接:https://nongxue.top/p/daima/4.html

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 当前版本
  • 目标
  • 涉及文件
    • /Joe/core/function.php (必须)
      • /Joe/core/core.php (必须)
        • /Joe/public/comment.php (必须)
          • /Joe/assets/js/joe.global.js (必须)
            • 自定义css(可选)
            • 最终效果
              • 未输入验证码提示
                • 验证码错误提示
                相关产品与服务
                验证码
                腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档