CakePHP: Creating a route usage https (SSL connection)

While playing in my workspace i need to make a route which should be use a secure path. That means https (SSL connection). So after googled for while i got the idea. Basically what i need is.. when an user in my sing in page will go through via the ssl connection. After entering user name and password will validated and redirect in to another location. So usually user will go through in https protocol then again redirected into http.

Here what i did;

Well, obviously i use cake’s component

1. Create a file ssl.php into app/controllers/components/
paste this code

class SslComponent extends Object {

	var $components = array('RequestHandler');

	var $Controller = null;

	function initialize(&$Controller) {
		$this->Controller = $Controller;
	}

	function force() {
		if(!$this->RequestHandler->isSSL()) {
			$this->Controller->redirect('https://'.$this->__url(443));
		}
	}

	function unforce() {
		if($this->RequestHandler->isSSL()) {
			$this->Controller->redirect('http://'.$this->__url());
		}
	}

	/**This method updated from John Isaacks**/
	function __url($default_port = 80)
	{
		$port = env('SERVER_PORT') == $default_port ? '' : ':'.env('SERVER_PORT');
		return env('SERVER_NAME').$port.env('REQUEST_URI');
	}
}

you can find it also here but i added unforce() 😉

3. Now, in my case only when user click in to sign in or lend now, I need the https connection. Thats why, in my home controller i added this beforeRender() method, but make sure you assign this Ssl component.

var $components = array( 'Ssl' );
public function beforeRender(){

$action = array( 'signin', 'lendnow' );

if( in_array( $this->params['action'] , $action ) ){

     $this->Ssl->force();
}else{
     $this->Ssl->unforce();
}

}

So, i will create a secure connection with my apache server.
4. User now enter their user name and password and submit

5. If anyone click beside this they will have only http connection

That’s it

enjoy 😉

About Tanveer
RIA (Rich Internet Application) Developer with a wide variety of business applications. Particularly interested in client/server and relational database design. Always interested in migration projects, as well as close interaction with the DB manufacturers.

54 Responses to CakePHP: Creating a route usage https (SSL connection)

  1. Rajib Deb says:

    Nice Article 🙂

  2. Tanveer says:

    hiii rajib ..
    Thanks for visiting my weblog man 😉
    m appreciate ur comment

  3. Tanveer says:

    u welcome chris 😉

  4. Richard says:

    nice little component!

    Once thing that might also be work looking at is the “requireSecure” method of the built-in security component, which on the surface seems like it might do the same thing.

  5. Pingback: Conexiones HTTP seguras (https) en CakePHP 1.2 | Blog cakephp en español por Hospedaxes

  6. Bảo Nam says:

    thanks for your share!

  7. Tanveer says:

    You welcome Nam

  8. Jeroen den Haan says:

    Hi, thanks for sharing your thoughts. While looking for info on implementing SSL in a CakePHP app, I also ran into the following article. It looks like a good solution, because it utilizes Cake’s default way of doing stuff like this. In your example, I figure you wouldn’t need to use a custom component… hope it helps.

    http://techno-geeks.org/2009/03/using-the-security-component-in-cakephp-for-ssl/

  9. spnkychnk says:

    I am getting this error. in the before render function.

    syntax error, unexpected ‘&’

    please help.

  10. Tanveer says:

    plz try now.. and let me know it works

  11. prashant says:

    Hi,
    I used ur script url shows with https but it says unable to connect. It shows browser can not connect to server. So there is any setting I have to do for running this? In phpinfo I seen server supports for https.

    Thanks,
    Prashant….

  12. prashant says:

    Hi,
    This works for me but there is one problem.I created one form in cakephp, after submit of this form some hidden fields are taken this are set to some variables also some mysql queries are present after that $this->ssl->force is used. Now it looses the data from $this->data also result of mysql query not take on https. So, what can I have to do for data?

    Thanks & Regards,
    Prashant

    • Tanveer says:

      hello prashant,
      Well, I am not clear what you are trying to do. But I guess you should follow these simple rule. Force https before the main workflow. After done all your work then back to http. Something like when click singup->force https->do whatever you want->load data->go back to http. Another thing be careful about beforeRender(). You have to set the action link correctly. Hope this will work.

  13. Sameer says:

    Hi ..
    Good article but there is problem with session.
    when any one login from HTTP connection and then visit HTTPS enabled page and again it they visit HTTP enabled connection then session will be destroy.

  14. Pieter says:

    Hi,

    At my provider place there is a map for http and https. So when I want to use https for login do I need to copy all the cakephp stuff to the https map or am I totally wrong now.

    Thanks & regards,

    Pieter

    • Tanveer says:

      Hello Pieter,
      Thanks for visiting my site. Well, I do not think so!
      All you need to switch your server port from 80 (http) to 443 (https).

      Best,
      Tanveer

      • Pieter says:

        Hi Tanveer,

        Thanks, I think I have to ask my provider to use a single directory for housing SSL and non-SSL content. Now it is separated into httpdocs and httpsdocs, which means I have to copy all the cakephp stuff into httpdocs as well httpsdocs. Do you have any other suggestion.

        Regards, Pieter

      • Tanveer says:

        Hi Pieter,
        You welcome 🙂
        Well, I don’t think you need to separate like that (httpdocs and httpsdocs). Please correct my assumption, you do not want to hold your visitors for a certain state like (HTTP or HTTPS) as long as they are visiting your site.

        Here is an example,
        1. A visitor just visit like http://www.example.com
        2. In home page there is link button like ‘Log in’ -> https://www.example.com/login.php
        3. So when your visitor click on ‘Log in’ it will switch to https form http.
        4. User will provide credentials and after successful login it will redirect like http://www.example.com/welcome.php

        Hope you got my point. 😉

        Please don’t hesitate to make any comment regarding this issue.

        Looking forward to hear from you.

        Best,
        Tanveer

  15. Pieter says:

    Again thanks, your point is clear to me. I think my problem is that the https call is redirected to httpsdoc directory which is a physical directory at my provider place. So If I am clear then I need the CakePhp stuff in the httpsdoc directory as well. I tried to copy only the login.php into the httpsdoc but that fails. I works fine when I have all the cakephp stuff in the httpsdoc. I also called my provider and he can change the settings so that I can use a single directory for housing SSL and non-SSL content (he will charge money for this).

    Regards, Pieter

    • Tanveer says:

      Hello Piet,
      I understood your setuation.
      Anyway, thanks for your reply and you can knock me anytime you need 🙂 .

      Best, Tan

  16. Pingback: 2010 in review « Tanveer's Weblog

  17. John Isaacks says:

    Wouldn’t it be better to make the function like:

    function __url($default_port = 80)
     {
    	$port = env('SERVER_PORT') == $default_port ? '' : ':'.env('SERVER_PORT');
    
    	return env('SERVER_NAME').$port.env('REQUEST_URI');
    }
    

    Then in the force function it would be the same but in the unforce function you could call it like this:

    $this->__url(443)

    Saves duplicating a function.

  18. Vince says:

    Thanks for the code, works perfectly!

  19. wahyu says:

    thanks, it’s work fine 🙂

  20. Dodo says:

    Thanks for the code, I need exactly this and work fine 🙂

  21. Joe Mosh says:

    Has this been tested in CakePHP 2.0?

    • Tanveer says:

      Well, it was written when CakePHP 1.2 is in the market. So I am not sure whether it will work in 2 or not. But you can give a try. Best of luck.

      Thanks for visiting.

  22. shyam says:

    thank you man, you saved my day 🙂

  23. Davit says:

    Thanks for the article, I have tried to use it on cake 1.3, but I have got this error

    SSL connection error
    Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring a client authentication certificate that you don’t have.

    I guess I am doing smth wrong.
    Could you, please, help me to figure out this problem ?
    THanks

  24. Kendall says:

    Hi there, You’ve done an incredible job. I’ll certainly
    digg it and personally suggest to my friends. I’m sure they’ll be benefited from this site.

  25. Excellent way of telling, and fastidious piece of writing to take data about my
    presentation focus, which i am going to deliver in academy.

  26. I leave a comment whenever I like a post on a blog or I have something to contribute to the conversation. It is a result of the fire communicated in the post I looked at.
    And on this post CakePHP: Creating a route usage
    https (SSL connection) | Tanveer’s Weblog. I was excited enough to post a comment
    😉 I actually do have 2 questions for you if
    you usually do not mind. Could it be simply me or does
    it appear like some of the responses appear
    like coming from brain dead visitors? 😛 And, if you are
    posting on additional online social sites, I’d like
    to follow everything new you have to post. Could you list the complete urls of your public pages like your linkedin profile, Facebook
    page or twitter feed?

  27. Arlene says:

    What a stuff of un-ambiguity and preserveness of valuable knowledge
    concerning unpredicted feelings.

  28. There’s definately a great deal to know about this topic.
    I really like all of the points you’ve made.

  29. It’s an amazing paragraph in favor of all the web viewers; they will obtain benefit
    from it I am sure.

  30. What i do not understood is if truth be told how you’re not really a lot more smartly-preferred than you might be right now.
    You are very intelligent. You understand therefore significantly
    in the case of this matter, produced me in my opinion imagine it from a lot of various angles.

    Its like women and men aren’t interested until it’s something to accomplish with Woman gaga!
    Your personal stuffs nice. At all times handle
    it up!

  31. Hey! I could have sworn I’ve been to this site before but after checking through some of the post
    I realized it’s new to me. Anyhow, I’m definitely delighted
    I found it and I’ll be bookmarking and checking
    back frequently!

  32. Hey There. I found your blog using msn. This is a really well written article.
    I’ll make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I will definitely return.

Leave a reply to Dodo Cancel reply