Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Controller Force HTTPS [closed]

Tags:

php

yii

I would like to know how to force HTTPS (SSL) at Yii Controller Action.

like image 234
Luciano Nascimento Avatar asked Oct 22 '12 10:10

Luciano Nascimento


2 Answers

Take a look at this article http://www.yiiframework.com/forum/index.php/topic/25407-forcing-https-in-yii/

class HttpsFilter extends CFilter {
    protected function preFilter( $filterChain ) {
        if ( !Yii::app()->getRequest()->isSecureConnection ) {
            # Redirect to the secure version of the page.
            $url = 'https://' .
                Yii::app()->getRequest()->serverName .
                Yii::app()->getRequest()->requestUri;
                Yii::app()->request->redirect($url);
            return false;
        }
        return true;
    }
}

And even this for more details.

like image 144
Bogdan Burym Avatar answered Oct 12 '22 05:10

Bogdan Burym


If you just want to apply https force onto your entire application, which is what I needed, you can put this in your protected/components/Controller.php:

  public function beforeAction($action) {
    if( ! Yii::app()->getRequest()->isSecureConnection ) {
      $url = 'https://' . 
        Yii::app()->getRequest()->serverName . 
        Yii::app()->getRequest()->requestUri;
      Yii::app()->request->redirect($url);
      return false;
    }
  }

This is a cleaner solution than filters if you need site-wide https, because with filters you have to apply an array_merge with the parent controller in all children controllers you create. If you miss one, no https force for that controller. The minor drawback to this is that it is called after filters have been called, meaning that more processing has been done than we usually want before redirection.

If your needing it on a controller by controller or an action by action basis, filters are what your looking for.

like image 40
Nick Gronow Avatar answered Oct 12 '22 05:10

Nick Gronow