本教程顯示瞭如何使用PHP,jQuery和Bootstrap快速實現基本的Ajax Captcha。 雖然不安全,但它提供了一種簡單,可自定義的解決方案,用於防止自動化表單提交。 這是需要快速,簡單的驗證碼而沒有recaptcha的複雜性的情況。
密鑰功能:
示例顯示驗證驗證功能(如果提供的話,鏈接到演示將在此處鏈接)。
[如果提供的話,驗證演示的圖像將去這裡]
>下載:完整的源代碼可在github上獲得(鏈接到GitHub repo,如果提供的話,將在此處使用)。
實現:驗證碼實現由HTML,jQuery和PHP組件組成。
1。 html(使用bootstrap):
<code class="language-html"><label class="" for="captcha">*Please enter the verification code shown below.</label> <div id="captcha-wrap"> <img src="/static/imghwm/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/imghwm/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"></code>2。 jQuery:
此jQuery代碼使用AJAX處理驗證碼刷新和驗證。 它利用jQuery Validate插件的
規則進行服務器端驗證。>
remote
<code class="language-javascript">$(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(); });</code>3。 php(newcaptcha.php):
此php腳本生成新的驗證碼圖像並將代碼存儲在會話變量中。
<code class="language-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); ?></code>4。 php(checkcaptcha.php):
此腳本將對會話變量驗證用戶的CAPTCHA輸入。
請記住調整文件路徑和字體設置以匹配您的項目結構。 這提供了一個功能功能,但基本的驗證碼系統。 為了獲得更高的安全性,請考慮使用更強大的解決方案,例如recaptcha。
以上是Easy JQuery Ajax php Catpcha -2分鐘設置的詳細內容。更多資訊請關注PHP中文網其他相關文章!