yii 驗證碼那點事兒

來源:互聯網
上載者:User

標籤:blog   io   os   使用   ar   檔案   div   sp   cti   

今天要使用yii驗證碼, 不過, 這個驗證碼是整站通用的, 也就是說, 有個表單的提交是使用ajax方式來提交, 整站, 不管在哪個地方, 都能點出來此視窗, 來提交資訊

關於yii驗證碼, framework/web/widgets/captcha/CCaptcha.php裡, 它源碼裡有這麼一部分

>---protected function renderImage()>---{>--->---if(!isset($this->imageOptions[‘id‘]))>--->--->---$this->imageOptions[‘id‘]=$this->getId();>--->---$url=$this->getController()->createUrl($this->captchaAction,array(‘v‘=>uniqid()));>--->---$alt=isset($this->imageOptions[‘alt‘])?$this->imageOptions[‘alt‘]:‘‘;>--->---echo CHtml::image($url,$alt,$this->imageOptions);>---}

可以看得到, 它每個驗證碼的產生, 驗證都是附著於當前控制器的, 所以, 對於整站通用的, 預設是行不通的. 

換個思路, 既然知道ajax訪問的路徑, 那就修改預設的方法, 讓其載入時, 都訪問同一控制器, 可以把 framework/web/widgets/captcha/CCaptcha.php 這個檔案複製一份, 放至項目下的 protected/widgets 目錄下, 名字自己定, 我在這裡定CommonCaptcha.php, 在設定檔 main.php 裡設定自動匯入(import)

<?phpreturn array(    ‘import‘ => array(            ‘application.widgets.*‘,    ),);?>

然後, 可以在複製過來的檔案裡搜尋    ‘getController‘ , 不出意外的話, 是可以搜尋到兩個的.

第一個 $url=$this->getController()->createUrl($this->captchaAction,array(‘v‘=>uniqid()));

可修改為 $url=Yii::app()->createUrl(‘/onlineService/captcha‘,array(‘v‘=>uniqid()));

第二個 $url=$this->getController()->createUrl($this->captchaAction,array(CCaptchaAction::REFRESH_GET_VAR=>true));

可修改為 $url=Yii::app()->createUrl(‘/onlineService/captcha‘,array(CCaptchaAction::REFRESH_GET_VAR=>true));

 

也就是不使用擷取的控制器, 而是指定控制器, 指定驗證碼的路徑. 

然後在控制器裡, 就可以使用

$this->createAction(‘captcha‘)->getVerifyCode();

這句代碼, 在onlineService控制器裡擷取驗證碼, 然後對比post過來的驗證碼, 就可以了, 這樣, 也無需在model裡再多加一個驗證的參數了.

至此, 驗證Ok

 

yii 驗證碼那點事兒

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.