【问题标题】:Yii captcha not working with blogYii 验证码不适用于博客
【发布时间】:2026-01-04 19:50:01
【问题描述】:

我已在此处应用所有其他解决方案来解决损坏的 yii 验证码,但无济于事。所以我要添加我自己的问题。

我已经阅读了 yii 博客教程 (http://www.yiiframework.com/doc/blog/),但我不想让 cmets 获得批准,而是希望在评论表单中有一个验证码。我已将此添加到评论表单视图中:

    <?php if(CCaptcha::checkRequirements()): ?>
    <div class="row">
            <?php echo $form->labelEx($model,'verifyCode'); ?>
            <div>
            <?php $this->widget('CCaptcha'); ?>
            <?php echo $form->textField($model,'verifyCode'); ?>
            </div>
            <div class="hint">Please enter the letters as they are shown in the image above.
            <br/>Letters are not case-sensitive.</div>
            <?php echo $form->error($model,'verifyCode'); ?>
    </div>
    <?php endif; ?>

而在 CommentController 中,accessRules() 变为:

public function accessRules()
{
        return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                        'actions'=>array('index','view', 'captcha'),
                        'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                        'actions'=>array('create','update'),
                        'users'=>array('@'),
                ),
                array('allow', // allow admin user to perform 'admin' and 'delete' actions
                        'actions'=>array('admin','delete'),
                        'users'=>array('admin'),
                ),
                array('deny',  // deny all users
                        'users'=>array('*'),
                ),
        );
}

我在 CommentController 中覆盖了 actions():

public function actions()
{
    return array(
        // captcha action renders the CAPTCHA image displayed on the contact page
        'captcha'=>array(
            'class'=>'CCaptchaAction',
            'backColor'=>0xD99D25,
        ),
    );
}  

在 Comment 模型中,我添加了一条新规则:

array('verifyCode', 'captcha', 'on' => 'insert', 'allowEmpty'=>!Yii::app()->user->isGuest)

和新的公共成员:

public $verifyCode;

联系表单上的验证码可以正常工作。但是在评论表单中,图像已损坏,并且刷新它的链接不起作用。有什么想法吗?

【问题讨论】:

    标签: php yii


    【解决方案1】:

    我将此代码添加到博客演示中,看起来对验证码的请求将发送到 PostController 而不是 CommentController。如果您将验证码操作添加到 PostController,它应该可以工作。

    【讨论】:

      【解决方案2】:

      您是否打开了萤火虫或网络检查器?它对验证码请求给出什么响应?

      【讨论】:

      • 感谢您的回复。我使用了 firbug,当我刷新联系表单上的验证码时,它会向验证码发出 2 个 GET 请求?refresh=1&_=1357396271704,然后是验证码?v=50e8392fcc7a9。但是在 blog 下,向 captcha?refresh=1&_=1357396217245 发出请求,但响应为空,然后向 site/login 发出请求......
      • 尝试像这样调用您的验证码小部件:$this->widget('CCaptcha', array('captchaAction'=>'comment/captcha'))。文档说,验证码请求是向当前控制器发出的,并且您的评论表单似乎显示在另一个控制器的操作中。