本教程显示了如何使用PHP,jQuery和Bootstrap快速实现基本的Ajax Captcha。 虽然不安全,但它提供了一种简单,可自定义的解决方案,用于防止自动化表单提交。 这是需要快速,简单的验证码而没有recaptcha的复杂性的情况。
密钥功能:
示例显示验证验证功能(如果提供的话,链接到演示将在此处链接)。
[如果提供的话,验证演示的图像将去这里]
>下载:完整的源代码可在GitHub上找到(链接到GitHub Repo,如果提供的话,将转到此处)。
实现:验证码实现由HTML,jQuery和PHP组件组成。
1。 html(使用bootstrap):
<label class="" for="captcha">*Please enter the verification code shown below.</label> <div id="captcha-wrap"> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174028207285395.jpg" class="lazy" alt="Easy jQuery AJAX PHP Captcha - 2 minute setup " /> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt="Easy jQuery AJAX PHP Captcha - 2 minute setup " /> </div> <input class="narrow text input" id="captcha" name="captcha" type="text" placeholder="Verification Code" />
此jQuery代码使用AJAX处理验证码刷新和验证。 它利用jQuery Validate插件的
规则进行服务器端验证。>
remote
$(function() { WEBAPP = { settings: {}, cache: {}, init: function() { this.cache.$form = $('#captcha-form'); // Assumes your form has id="captcha-form" this.cache.$refreshCaptcha = $('#refresh-captcha'); this.cache.$captchaImg = $('img#captcha'); this.cache.$captchaInput = $(':input[name="captcha"]'); this.eventHandlers(); this.setupValidation(); }, eventHandlers: function() { WEBAPP.cache.$refreshCaptcha.on('click', function(e) { WEBAPP.cache.$captchaImg.attr("src", "/php/newCaptcha.php?rnd=" + Math.random()); }); }, setupValidation: function() { WEBAPP.cache.$form.validate({ onkeyup: false, rules: { "captcha": { required: true, remote: { url: '/php/checkCaptcha.php', type: "post", data: { code: function() { return WEBAPP.cache.$captchaInput.val(); } } } } // Add other form field validation rules here as needed }, messages: { "captcha": { required: "Please enter the verification code.", remote: "Verification code incorrect, please try again." } // Add other form field error messages here as needed }, submitHandler: function(form) { // Handle successful form submission here (e.g., AJAX submission) } }); } }; WEBAPP.init(); });
此php脚本生成新的验证码图像并将代码存储在会话变量中。
<?php session_start(); $string = ''; for ($i = 0; $i < 6; $i++) { $string .= chr(rand(97, 122)); } $_SESSION['captcha'] = $string; $dir = '../fonts/'; // Path to your fonts directory $image = imagecreatetruecolor(165, 50); $font = "PlAGuEdEaTH.ttf"; // Your font file $color = imagecolorallocate($image, 113, 193, 217); $white = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, 399, 99, $white); imagettftext($image, 30, 0, 10, 40, $color, $dir . $font, $_SESSION['captcha']); header("Content-type: image/png"); imagepng($image); ?>
此脚本将对会话变量验证用户的CAPTCHA输入。
请记住调整文件路径和字体设置以匹配您的项目结构。 这提供了一个功能功能,但基本的验证码系统。 为了获得更高的安全性,请考虑使用更强大的解决方案,例如recaptcha。
以上是Easy JQuery Ajax php Catpcha -2分钟设置的详细内容。更多信息请关注PHP中文网其他相关文章!