Wednesday, September 16, 2009

CakePHP Tip: Creating https:// links

It's always better to use CakePHP's HTML helper to create relative links that will make your app portable. What if you need to create relative link that will use https:// instead of the default http://? This will be useful if most of your site uses http:// but some pages need to be secure (eg. registration or checkout page). Let's say your link is pointing to /pages/register, here's how to do it:
echo $html->link("Register", str_replace('http://', 'https://',
$html->url("/pages/register", true)));

What happens here? we use $html->url() to create a relative URL, and set the 2nd parameter to true so it will return the full URL (eg. http://domain.com/pages/register) and then replace http:// with https://, we then pass that URL to HTML helper's link() method to create a HTML link.

Note that you don't need to do this if the originating page is already using https://. If that is the case, then all relative links will also use https:// by default.

1 comment:

  1. Thank you. This is better than the method described here http://stackoverflow.com/questions/1431129/cakephp-secure-link-using-html-helper-link-method

    ReplyDelete