Home > Article > Backend Development > PHP development framework Yii Framework tutorial (20) UI component Captcha example
Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart, referred to as CAPTCHA), commonly known as verification code, is a public fully automatic program that distinguishes between computers and humans. In a CAPTCHA test, the computer as the server automatically generates a question for the user to answer. This question can be generated and judged by a computer, but only a human can answer it. Since computers cannot answer CAPTCHA questions, the user who answers the questions can be considered a human.
Yii Framework provides classes CCaptcha and CCaptchaAction to support verification codes. It should be noted that this function requires PHPGD extension support and can be queried through Yii's Requirements application:
If a Warning is displayed, you can turn on this function by installing the GD extension library and modifying PHP.ini.
CCaptcha also provides the method CCaptcha::checkRequirements() to detect whether the GD library is installed.
This example adds the Captcha function by modifying the Yii Framework Development Tutorial (16) UI component StarRating example. Only when the input verification code is correct, the user rating will be valid to avoid automatic scoring by the machine.
First, modify the DataModel, add an attribute verifyCode to store the verification code entered by the user, and add CCaptchaValidator verification to it.
class DataModel extends CFormModel{public $rating;public $verifyCode; public function rules(){ return array(array('rating,verifyCode', 'safe'), array('verifyCode','captcha','allowEmpty'=>!CCaptcha::checkRequirements()),); }}
Then modify the SiteController and add the actions method. The Captcha component uses CCaptchaAction by default, and its default ID is captcha.
public function actions() { return array( 'captcha'=>array( 'class' => 'CCaptchaAction', )); }
Now you can add the Captcha component in the View:
beginWidget('CActiveForm'); ?> errorSummary($model); ?>widget('CStarRating', array('model'=>$model,'attribute'=>'rating','name'=>'rating','value'=>3,)); ?> label($model,'verifyCode') ?> widget('CCaptcha'); ?>textField($model,'verifyCode') ?> endWidget(); ?>
The above is the PHP development framework Yii Framework tutorial (20) UI component Captcha example Content, for more related content, please pay attention to the PHP Chinese website (www.php.cn)!