Cakephp: Force SSL on certain actions

3.15.2012 | cakephp, PHP

After going here and there and implementing alot of solutions, I found that every post request is getting redirected to get even if it was with HTTPS because of the implementation of the ForceSSL in the manual, so my word to you, save your time and implement this simple solution. I have tested it on cakephp 2.0 however I think it wouldn’t mind to work on cakephp 1.3

First thing, we are going to define the actions that requires SSL, which I’ll name the secure actions

class AppController extends Controller {
    protected $secureActions = array(
    	'place_order',
    	'login',
    	'checkout'
    );
}

We are going to check if the current action is in our secure actions

function beforeFilter() {
        if (in_array($this->params['action'], $this->secureActions) 
            && !isset($_SERVER['HTTPS'])) {
                $this->forceSSL();
        }
}

Then we will implement a method to redirect to the same URI but with HTTPS

public function forceSSL() {
	$this->redirect('https://' . $_SERVER['SERVER_NAME'] . $this->here);
}
Be Sociable, Share!

Responses

thomas
4.15.2012

thx a lot omar for that post,

i get an 404 error when cake tries to redirect me to my login page, when HTTPS is called..do you know what to do about it?

thx 😉

Omar Shaban
4.18.2012

Are you sure the SSL Configured correctly in the virtual hosts? because it requires virtualhost on port 443

Felipe Marques
3.21.2013

You helped me a lot.

Tks Omar!

Henry
3.27.2013

Thank you, God bless you, your tutorial has helped me alot. in CakePHP 2.3

Prazi
4.06.2013

Thanks Omar. It was a great help.

Stephen Speakman
2.18.2015

Hi, I amended this to work a little different for my project.

http://pastie.org/private/rdaukzl6uow5tizhvarkna

By checking if $this->secureActions exists and is not empty before doing the rest of the logic, you can specify secureActions in each separate controller with no worry of conflicts.

Hope this helped

Comments