When making a request, I found that I entered the correct verification code, but the verification code error was prompted
Finally, I traced the code and found that if the Model did validate
separately before save
, then after the verification, The verification code will be regenerated
Then when our Model save
, it will also be verified by validate
. During verification, the verification code has been regenerated, so it will not match
<code>// 如果这里用到了验证码,就会出问题 $model = new Test(); $model->validate(); $model->save(); </code>
<code> // 这样是正确的 $model = new Test(); // 把需要验证的 attribute 放进去,排除验证码字段 $model->validate(array('test1','test2')); $model->save()</code>
We can see framework/web/ widgets/captcha/CCaptchaAction.php
You can easily find the problem
<code> <?php class CaptchaAction extends CCaptchaAction { public function validate($input, $caseSensitive) { $code = $this->getVerifyCode(); $valid = $caseSensitive ? ($input === $code) : !strcasecmp($input, $code); $session = Yii::app()->session; $session->open(); $name = $this->getSessionKey() . 'count'; if (!Yii::app()->request->isAjaxRequest) { $session[$name] = $session[$name] + 1; } // 这里会重新生成 if ($session[$name] > $this->testLimit && $this->testLimit > 0) { $this->getVerifyCode(true); } return $valid; } } </code>
The above introduces the solution to Yii's failure to enter the correct verification code verification, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.