When operating a website, we often encounter robots (bots) submitting a large number of spam comments or reviews, which not only affects the quality of the website content and increases the management burden, but may also have a negative impact on the reputation of the website.It is fortunate that AnQiCMS provides an integrated captcha mechanism that can effectively help us prevent this kind of abuse behavior.Next, let's see how to add a captcha for user comments or reviews in AnQiCMS.

Step 1: Enable the captcha feature in the background.

Firstly, we need to log in to the AnQiCMS admin interface and enable the core captcha feature.This step is to let the system know that captcha verification needs to be performed when handling user submitted messages or comments.

You can find this setting through the following path:

  1. Log in to your AnQiCMS backend.
  2. Find and click on it in the left navigation bar.“Function Management”.
  3. Select in the expanded feature list“Website Message Management”orContent Comment ManagementIf you want to protect messages and comments at the same time, both areas may need to be checked.
  4. After entering the management page, you will see a page named“Message and Comment Verification Code Function”The option. Usually, this is a toggle switch or a checkbox. Just switch its state to“Enable”, and then remember to click“Save”button to ensure the settings take effect.

Complete this step and the AnQiCMS backend will be ready for captcha verification.But, simply enabling it in the background is not enough, we also need to add the display and input fields for the captcha on the front-end page of the website.

第二步:修改前端模板,集成验证码表单

The captcha needs a place to display the image and provide an input box for users to fill in. This needs to be modified in your website's frontend template. Usually, the comment form is locatedguestbook/index.htmlTemplate, while the comment form may be locatedcomment/list.htmlin the template of the article detail page.

In the appropriate location of your comment or review form (such as above the submit button, or below the comment/review content input box), you need to add the following HTML code snippet:

<div style="display: flex; clear: both; margin-top: 15px;">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1; margin-right: 10px;">
  <img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" alt="验证码图片" />
</div>

Here are three key elements:

  • a hidden input box (captcha_id):It is used to store the unique identifier of the current captcha session, which users do not need to fill in, but the system will use it to match the captcha entered by the user.
  • a text input box (captcha):This is where the user actually enters the captcha they see.
  • An image tag (get-captcha):This tag will be used to display the dynamically generated captcha image.

Third step: Write JavaScript code to dynamically load captcha image

Since the captcha image is dynamically generated, it will be different each time the page is loaded or the captcha is refreshed, so we need a piece of JavaScript code to dynamically fetch and display it.This code will automatically retrieve the first captcha when the page is loaded and refresh it when the captcha image is clicked.

Add the following JavaScript code to the place where you introduce frontend JS in your website template, or directly below the modified form HTML snippet (using<script>Label it as follows:

<script>
  // 监听验证码图片的点击事件,用于刷新验证码
  document.getElementById('get-captcha').addEventListener("click", function (e) {
    // 发送请求到后台 API 获取新的验证码
    fetch('/api/captcha')
      .then(response => {
        // 解析响应为 JSON 格式
        return response.json()
      })
      .then(res => {
        // 更新隐藏字段 captcha_id 的值
        document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
        // 更新验证码图片的 src 属性,显示新的验证码图片
        document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
      }).catch(err =>{
        console.error("获取验证码失败:", err); // 错误处理
      });
  });
  // 页面加载后自动触发一次点击事件,以显示初始验证码
  document.getElementById('get-captcha').click();
</script>

If you are accustomed to using jQuery, you can also use the following more concise syntax:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 如果你的网站还没有引入jQuery,请先引入 -->
<script>
  // jQuery 调用方式
  $('#get-captcha').on("click", function (e) {
    $.get('/api/captcha', function(res) {
      $('#captcha_id').attr("value", res.data.captcha_id);
      $('#get-captcha').attr("src", res.data.captcha);
    }, 'json');
  });
  // 页面加载后自动触发一次点击事件,以显示初始验证码
  $('#get-captcha').click();
</script>

This JavaScript code's core logic is: When the page loads, it will send data to the AnQiCMS backend/api/captchaInterface sends a request to obtain a verification code image URL and a corresponding ID. Then, it will display this image in<img>the tag and store the ID in the hiddencaptcha_idInput box. This process will repeat when the user clicks the picture, generating a new captcha.

Step 4: Save and test

Complete all modifications and save your template file. Now, visit the page on your website that contains a comment or feedback form.

You should see an additional captcha image and an input box below the form.Try entering the characters from the image in the input box, then submit your comment or message.If the captcha is entered correctly, your content will be published normally; if entered incorrectly, the system will prompt that the captcha is incorrect.This indicates that the captcha function has been successfully run, and it can effectively prevent the harassment of automated robots.

By following these simple steps, your AnQiCMS website can effectively utilize the captcha mechanism, greatly reduce spam information, and make the content environment of the website healthier and more orderly.


Common Questions (FAQ)

1. Why do I still not see the captcha on the front-end form even though I have enabled the '留言评论验证码功能' in the AnQiCMS backend?

This is usually because you have only enabled the feature in the background, but have not added the required HTML elements and JavaScript code to display the captcha in the front-end template.The backend settings only enable the verification code validation logic, and the presentation of the verification code (image display and input box) needs to be manually integrated into your website template.Please make sure you have added the corresponding HTML and JavaScript code to the template file for comments or reviews as per the second and third steps in this article.

2. What type of captcha does AnQiCMS provide? Can I customize its style or replace it with another type of captcha?

3. How to troubleshoot when the captcha image cannot be loaded or there is no reaction when refreshing?

If the captcha image does not display or cannot be refreshed, it may be due to the following reasons:

  • Network issue or API path error:Check the browser's developer tools (F12), view the network request, and confirm/api/captchaIs the interface called correctly, is there any returned data, and is the status code 200.
  • JavaScript error:Check in the Console (control panel) in the developer tools