自定义 PHP 验证码


Custom PHP CAPTCHA

>我编写了一个显示随机方程的PHP函数。 如果未提供正确答案,则提交失败。 等式是这样的:

[ 随机数字或文本数字 ] [ 随机选择 +,-,x ] [ 随机数字或文本编号 ]= ?

因此,您可能会看到:8+2=?,或七 - 4 = ?,依此类推

我手动测试了这个,它似乎工作得很好。 我无法正确回答验证码。 然而,尽管有这个验证码,但某事或某人正在发布垃圾邮件。 所以我的问题是,有没有程序可以解决这个问题?

这是我的表格:

<form action="scripts/handler_post.php" method="post" id="gb_form">
                    <h3>Leave us a comment:</h3><br />
                    <div id="form_msg"><?php echo $msg; ?></div>
                    <input type="text" name="name" value="Your Name" />
                    <textarea name="message">Your Message</textarea>
                    <?php include('includes/bmw_captcha.php'); ?> 
                    <div style="color:red; font-size:90%;">*What does <?php echo $array_num1[1] . " " . $array_calculation[0] . " " . $array_num2[1] . " = "; ?>    
                    <input type='text' maxlength='2' name='captcha' style="color:#640513; width:25px;" />?</div>
                    <div><span style="font:italic 90% Arial; color:#666;">(For security purposes, please answer this CAPTCHA problem.)</span></div>
                    <input type="hidden" name="captcha_answer" value="<?php echo $array_calculation[1]; ?>" />
                    <input type="submit" name="submit_button" value="Post" />
                </form>

下面是处理表单的脚本:

// submitted values
$name       = clean_string( $_POST['name'] );
$message    = clean_string( $_POST['message'] );
$captcha    = clean_string( $_POST['captcha'] );
$captcha_ans= clean_string( $_POST['captcha_answer'] );
// check if name var is empty or contains digits
if( empty($name) || (strcspn( $name, '0123456789' ) != strlen( $name )) ) 
{ header( 'Location: /guestbook.php?msg=n' ); }
else if( empty($message) )
{ header( 'Location: /guestbook.php?msg=m' ); }
else if( empty($captcha) || $captcha != $captcha_ans )
{ header( 'Location: /guestbook.php?msg=cap' ); }
else 
{
    $query = "
            INSERT INTO $table_posts ( id, name, message, timestamp ) 
            VALUES( 0, '"$name'", '"$message'", now() )
    ";
    $result = $db_connect->query( $query ); // execute the query
    if( $result )
    {       
        header('Location: ../guestbook.php?msg=1');
    }
    else
        header('Location: ../guestbook.php?msg=2');
}

您应该将验证码的答案存储在会话变量中。通过表单以明文形式发送它,使机器人可以将字段设置为所需的任何值。机器人通常会将所有未知字段设置为某个字符串,例如 ijhsg87dfb34,因此如果它将captchacaptcha_answer字段设置为相同的值,它将成功!

一个非常简单的方法是使用隐藏字段,在处理 POST 的脚本中,您检查该字段是否已填写,如果是,则它是一个 BOT 等,因为普通用户永远不会看到该字段,但 BOT 等只是盲目填写每个字段。

您可以尝试非验证码安全表单。检查这个http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs