How to ensure that a captcha is displayed when users submit comments or messages to prevent robot abuse?

Calendar 👁️ 93

When operating a website, we often encounter robots (bots) submitting a large number of spam messages or comments, which not only affects the quality of the website content, but also increases the management burden, and may have a negative impact on the reputation of the website.Fortunately, AnQiCMS provides an integrated captcha mechanism that can effectively help us prevent such abuse.Let's take a look together at how to add a captcha for user messages or comments in AnQiCMS.

Step 1: Enable captcha functionality in the background

Firstly, we need to log in to the AnQiCMS backend management interface and enable the core captcha function.This step is to let the system know that captcha verification is required when processing user submitted messages or comments.

You can find this setting by following the following path:

  1. Log in to your AnQiCMS backend.
  2. Find and click in the left navigation bar“Function Management”.
  3. Select in the expanded feature list“Website Message Management”or“Content Comment Management”. If you want to protect both messages and comments, both areas may need to be checked.
  4. After entering the management page, you will see a name called“留言评论验证码功能”option. Usually, this is a toggle button or checkbox. Just switch its state to“Enable”, then remember to click“Save”Button, ensure the settings take effect.

After completing this step, AnQiCMS's backend is ready for captcha verification.But, it is not enough to enable it only in the background, we also need to add the display and input fields of the captcha on the front page of the website.

Step two: Modify the front-end template and integrate the captcha form.

A captcha needs a place to display an image and provide a text box for the user to fill in. This needs to be modified in your website's front-end template. Usually, the message form is located atguestbook/index.htmlTemplate, while the comment form may be locatedcomment/list.htmlor in the template of the article details page.

In an appropriate location on 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>

It includes 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 uses it to match the captcha entered by the user.
  • A text input box(captchaThis is the place where users actually input the captcha they see.
  • A picture tag(get-captchaThis label will be used to display the dynamically generated captcha image.

Step 3: Write JavaScript code to dynamically load captcha image

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

Add the following JavaScript code to the place where you introduce frontend JS in your website template, or directly below the modified form HTML section (using<script>Tag enclosed:

<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 method:

<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>

The core logic of this JavaScript code is: when the page loads, it will send to the AnQiCMS backend/api/captchaThe interface sends a request to obtain an captcha image URL and a corresponding ID. Then, it will display the image in<img>the tag and store the ID in the hiddencaptcha_idInput box. When the user clicks the image, this process will repeat and generate a new captcha.

Step 4: Save and test.

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

You should see an image of a captcha and an input box below the form.Try to enter the characters from the image in the input box, then submit your message or comment.If the captcha is entered correctly, your content will be published normally;If the input is incorrect, the system will prompt that the captcha is incorrect. This indicates that the captcha function has been successfully run and 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, and make the content environment of the website healthier and more orderly.


Frequently Asked Questions (FAQ)

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

This is usually because you have only enabled the feature in the background, but have not added the necessary HTML elements and JavaScript code to display the captcha in the front-end template.The backend settings only enable the captcha verification logic, and the presentation of the captcha (image display and input box) needs to be manually integrated into your website template.Make sure you have added the corresponding HTML and JavaScript code according to 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?

The current AnQiCMS provides a built-in image captcha mechanism.It mainly displays randomly generated image characters for users to recognize and input.About style customization, you can adjust the size, border, and other display effects of the captcha image container by modifying the front-end CSS, but the font, color, and other aspects of the image itself are usually generated by the system backend, and the options for direct customization may be limited.If you need to switch to other types of verification codes (such as sliding verification, behavioral verification, etc.), it may require deeper secondary development or waiting for future version feature updates.

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

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

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

Related articles

How to generate random placeholder text to simulate real content display during template development?

During the process of website template development, we often encounter a challenge: how to fill the page to check the layout, style, and responsiveness before the real content is ready?If the template is empty or only has a few lines of simple text, it is difficult to evaluate the design effect directly.This is a very useful technique for generating random placeholder text. AnQiCMS (AnQiCMS) is an efficient and customizable content management system that fully considers the needs of template developers at this stage.

2025-11-08

How to perform basic arithmetic operations on numbers in templates and display the results?

In website operation, we often need to dynamically display some numerical information, such as total product price, percentage of article reading, discounted price, and so on.The template system provided by AnQi CMS is powerful, it adopts syntax similar to the Django template engine, allowing us to easily implement these requirements when displaying content, perform basic arithmetic operations directly in the template, and display the results.### Master basic arithmetic operations in templates The most direct way to write arithmetic expressions in Anqi CMS templates is within double curly braces `{{ }}`

2025-11-08

How to concatenate the elements of an array into a string separated by a specified delimiter for display?

When managing and displaying content in Anqi CMS, we often encounter situations where we need to merge a group of related information into a coherent text.For example, a product may have many characteristics, and we hope to display the list of these characteristics uniformly with commas or slashes.Or perhaps, an article is associated with multiple keyword tags, and we want to summarize these tags into a single line of text.At this time, the powerful template filter of Anqi CMS can be put to good use, especially the `join` filter, which can help us easily achieve this goal.### Understand the `join` filter

2025-11-08

How to convert timestamp data stored in the background into a readable date and time format for display?

When managing website content in Anqi CMS, we often encounter situations where we need to display dates and times.However, the time information stored in the background database is usually in the form of timestamps, which is very efficient for machine processing, but difficult for users to read directly.For example, you might see a string like `1609470335`, which represents a specific moment, but we want it to be displayed in a more friendly format like "2021 January 1 at 12:25:35".fortunately

2025-11-08

How to retrieve and display specific content from a specified site in a multi-site management environment?

In today's changing network environment, many businesses and content operators are no longer satisfied with a single site.Scenarios where there are multiple brands, product lines, or the need for multilingual promotion are becoming increasingly common.AnQiCMS (AnQiCMS) is exactly under such needs, providing powerful multi-site management capabilities, allowing us to easily manage multiple content platforms with a single system.But having multi-site functionality is not enough. Often, we need to display specific content from one site on another site, to achieve resource sharing and content synergy.For example, the main site wants to display the latest products of a child site

2025-11-08

How to debug the structure, type, and value of display variables in a template to help troubleshoot display issues?

During the template development process of Anqi CMS, we sometimes encounter situations where variables do not display as expected or the displayed content is incorrect.This may affect the normal functioning of the website, and may also cause deviations in content display, reducing the user experience.We need an efficient and intuitive tool to help us quickly locate the problem.The Anqi CMS provides a very practical built-in filter——`dump`, which can help us clearly view the structure, type, and current value of any variable in the template.

2025-11-08

How to format a floating-point number to a specified precision (number of decimal places) for display?

In AnQiCMS, the flexibility of content display is one of its core advantages.When dealing with floating-point numbers that require precise display of decimal places, understanding how to utilize its powerful template engine function is particularly important.Ensure that numbers are presented in the expected format for displaying product prices, statistical data, or technical parameters, which can greatly enhance user experience and the professionalism of the website.The Anqi CMS template syntax borrows from the Django template engine, providing rich filters (Filters) to process and format data.Formatting for floating-point numbers

2025-11-08

How to automatically convert URLs and email addresses in text to clickable links and display them?

In website content management, we often encounter scenarios where we need to display various links and email addresses in articles or pages.Manually converting this text to clickable HTML links is time-consuming and prone to errors, especially when the amount of content is large, and the workload is惊人的。AnQi CMS fully understands this pain point of users, built-in efficient and intelligent text processing mechanism, can automatically identify and convert URLs and email addresses, greatly improve the efficiency of content publishing and user browsing experience

2025-11-08