You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress联系表单随机数人机验证实现及变量数学运算求解

Hey there! Let's tackle your two WordPress-related problems one by one—first the math-based CAPTCHA for contact forms, then safely evaluating the math expression with those variables.

1. WordPress联系表单实现随机数人机验证功能

Here's a step-by-step implementation that ties directly into the variables you mentioned:

Step 1: Generate random numbers, operator, and store the correct answer

First, we'll generate the random values and calculate the correct answer, then store it in a session to verify later. We'll handle division specially to avoid non-integer results (since users will input whole numbers):

// Start session if not already active
if (!session_id()) {
    session_start();
}

// Generate random numbers (adjust range as needed)
$number1 = rand(1, 10);
$number2 = rand(1, 10);

// Define allowed operators
$operators = ['+', '-', '*', '/'];
$operator = $operators[array_rand($operators)];

// Ensure division results in integer (avoid fractions for user convenience)
if ($operator === '/') {
    $number1 = $number2 * rand(1, 5); // Make number1 a multiple of number2
}

// Calculate correct answer (we'll build this function next)
$correct_answer = calculate_math_expression($number1, $number2, $operator);

// Store answer in session for validation
$_SESSION['contact_form_captcha_answer'] = $correct_answer;

Step 2: Add the CAPTCHA field to your contact form

Insert this HTML where you want the CAPTCHA to appear in your form:

<div class="captcha-container">
    <label for="captcha_answer">Human Verification: <?php echo "{$number1} {$operator} {$number2} ="; ?></label>
    <input type="number" id="captcha_answer" name="captcha_answer" required>
</div>

Step 3: Validate the CAPTCHA on form submission

When processing the form, check if the user's input matches the stored correct answer:

// Start session
session_start();

// Get user's input
$user_answer = isset($_POST['captcha_answer']) ? intval($_POST['captcha_answer']) : '';

// Validate answer
if ($user_answer !== $_SESSION['contact_form_captcha_answer']) {
    wp_die('Oops! Your math answer is incorrect. Please try again.');
}

// Clear the session to prevent reuse
unset($_SESSION['contact_form_captcha_answer']);

// Proceed with your form submission logic (send email, save to DB, etc.)
2. Safely evaluate the math expression with $number1, $number2, $operator

Important: Never use eval() for this! It’s a massive security risk if any part of the variables could be user-controlled. Instead, use a switch statement or a lookup array to safely map operators to calculations:

Option 1: Switch Statement (easy to read)

function calculate_math_expression($num1, $num2, $op) {
    switch ($op) {
        case '+':
            return $num1 + $num2;
        case '-':
            return $num1 - $num2;
        case '*':
            return $num1 * $num2;
        case '/':
            // Add a safety check to avoid division by zero
            return $num2 !== 0 ? $num1 / $num2 : 0;
        default:
            throw new InvalidArgumentException("Unsupported operator: {$op}");
    }
}

Option 2: Lookup Array (concise, modern PHP)

Using arrow functions (PHP 7.4+):

function calculate_math_expression($num1, $num2, $op) {
    $operations = [
        '+' => fn($a, $b) => $a + $b,
        '-' => fn($a, $b) => $a - $b,
        '*' => fn($a, $b) => $a * $b,
        '/' => fn($a, $b) => $b !== 0 ? $a / $b : 0
    ];

    if (!isset($operations[$op])) {
        throw new InvalidArgumentException("Unsupported operator: {$op}");
    }

    return $operations[$op]($num1, $num2);
}

Both methods are safe, predictable, and avoid the security pitfalls of eval().

内容的提问来源于stack exchange,提问作者M.Islam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:56:20