When running a website, spam comments and malicious messages often cause headaches.They not only affect user experience, but may also consume server resources, even lowering the professional image of the website. 幸运的是,AnQi CMS 内置了验证码功能,可以帮助我们有效地过滤这些不期而至的客人,使网站环境更加清新。

Below, we will together learn how to enable and correctly display the captcha function in the website's comment and message form.

Step 1: Enable captcha functionality in the background

Firstly, we need to go to the management interface of the website backend. Find "Function Management" in the left navigation bar and then choose to enter "Website Message Management" or "Content Comment Management" according to your needs.These modules usually have a similar configuration item.

After entering the corresponding management page, you will see an option named "Whether to enable captcha" or something similar. Check it to enable and save the settings.

This step is crucial, it informs the Anqi CMS backend system that a captcha check needs to be performed when handling comment or message submissions.If the backend is not enabled, even if the code to display the captcha on the front end is added, the captcha will not work normally because the backend will not verify it.

Step 2: Modify the website template file to display the captcha

Next, we need to modify the website's front-end template file so that the user can see and enter the captcha when submitting the form. Usually, the message form is located in your template directory.guestbook/index.htmlIn the document, while the comment form may be in the template of the article or product details page (such asarchive/detail.htmlorproduct/detail.html) or a dedicated comment list template (comment/list.html).

Find the form you want to add the captcha to and add the following HTML and JavaScript code near the submit button.This code mainly includes three parts: a hidden input box for storing the captcha ID, a text input box for users to enter the captcha, and an image tag for displaying the captcha image.

<div style="display: flex; clear: both; align-items: center; margin-bottom: 15px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" style="flex: 1; padding: 10px; border: 1px solid #ccc; margin-right: 10px; border-radius: 4px;">
  <img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #eee; border-radius: 4px;" alt="验证码">
</div>

<script>
  // 获取验证码的函数
  function fetchCaptcha() {
    fetch('/api/captcha')
      .then(response => response.json())
      .then(res => {
        if (res.code === 0 && res.data) {
          document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
          document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
        } else {
          console.error('获取验证码失败:', res.msg);
        }
      })
      .catch(err => {
        console.error('请求验证码接口出错:', err);
      });
  }

  // 页面加载完成后立即获取一次验证码
  document.addEventListener('DOMContentLoaded', function() {
    fetchCaptcha();
  });

  // 点击验证码图片时刷新验证码
  document.getElementById('get-captcha').addEventListener("click", function () {
    fetchCaptcha();
  });
</script>

If you use the jQuery library on your website, you can also use the following more concise jQuery syntax:

<div style="display: flex; clear: both; align-items: center; margin-bottom: 15px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" style="flex: 1; padding: 10px; border: 1px solid #ccc; margin-right: 10px; border-radius: 4px;">
  <img src="" id="get-captcha" style="width: 150px; height: 40px; cursor: pointer; border: 1px solid #eee; border-radius: 4px;" alt="验证码">
</div>

<script>
  // jQuery 调用方式
  function fetchCaptchaWithJquery() {
    $.get('/api/captcha', function(res) {
      if (res.code === 0 && res.data) {
        $('#captcha_id').attr("value", res.data.captcha_id);
        $('#get-captcha').attr("src", res.data.captcha);
      } else {
        console.error('获取验证码失败:', res.msg);
      }
    }, 'json').fail(function(jqXHR, textStatus, errorThrown) {
      console.error('请求验证码接口出错:', textStatus, errorThrown);
    });
  }

  $(document).ready(function() {
    fetchCaptchaWithJquery(); // 页面加载后获取验证码
    $('#get-captcha').on("click", function () {
      fetchCaptchaWithJquery(); // 点击图片刷新验证码
    });
  });
</script>

This JavaScript code is responsible for sending to the/api/captchaThe interface initiates a request to obtain a new captcha image and the corresponding ID. Then, it will display the obtained captcha image in<img>the tag and fill the captcha ID into the hiddencaptcha_idWithin the input box. After the user enters the captcha, the system will use this ID to verify whether the input is correct.In order to make the captcha image and input box look more coordinated, some basic CSS styles have already been provided in the above example. You can adjust and beautify them according to the overall style of the website.

Place the above code snippet correctly in your comment or message<form>Inside the tag and make surecaptcha_id/captchaandget-captchaThe IDs of these elements are unique in your template to avoid conflicts.

By following these two simple steps, your Safe CMS website can effectively enable captcha functionality in comment and message forms.This can significantly reduce the disturbance of spam information, protect the purity of the website content, and improve the overall operational efficiency.Good user experience and website security are parallel, and CAPTCHA is an effective tool to balance both.


Frequently Asked Questions (FAQ)

1. Ask: Why does the captcha image not display even though I followed the steps?

Answer: This may be caused by several reasons. First, please confirm again whether you have checked and saved the option 'Whether to enable captcha' under 'Function Management' in the Anqi CMS backend for 'Website Message Management' or 'Content Comment Management'.Next, check the browser console (usually opened by pressing F12) for any failed network requests (404 or 500 errors) or JavaScript errors.Confirm your website can be accessed/api/captchaAccess the captcha interface path, and the data format it returns is correct. Finally, also check if the CSS style you added has accidentally hidden the captcha image.

2. Ask: I have enabled the captcha, but there are still spam comments submitted, what is the matter?

Answer: CAPTCHA can effectively filter out most automated, low-level forms of spam robots.However, for some more advanced robots, or spam comments released through manual operation, the captcha may not completely prevent.In this case, you can consider combining other content security features of Anqi CMS, such as sensitive word filtering, manual review mechanisms, or setting comment submission frequency limits to further enhance the preventive effect.

3. Ask: Can I change the display style of the captcha or replace it with another type?

Answer: The captcha function built into Anqi CMS usually provides a default image.