Posted By

dalethedeveloper on 01/27/10


Tagged

php ssl https silverstripe


Versions (?)

SilverStripe SSL switching by statics


 / Published in: PHP
 

A little function I add to the base PageController class that allows you to define what actions are explicitly SSL. It will put users in SSL when they access it and take them out of it when they navigate somewhere else. It is available in any controllers that extend PageController.

Be sure to add $this->_checkSSL(); to the Page_Controller's init() function.

  1. protected function _checkSSL() {
  2. $needSSL = $inSSL = $destURL = false;
  3. $inSSL = ( isset($_SERVER['SSL']) || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ) ? true : false;
  4.  
  5. // Get static $ssl_actions and see if we need to switch in or out of SSL
  6. if($all_ssl_actions = Object::combined_static($this, 'ssl_actions') and is_array($all_ssl_actions) ) {
  7. $action = $this->getRequest()->latestParam('Action'); // $this->getAction() always empty??
  8. if( in_array($action,$all_ssl_actions) or
  9. (in_array('index',$all_ssl_actions) and is_null($action) ) ) {
  10. $needSSL = true;
  11. }
  12. }
  13.  
  14. if( $needSSL and !$inSSL ){
  15. $destURL = str_replace('http:','https:', Director::absoluteURL($_SERVER['REQUEST_URI']));
  16. } elseif( !$needSSL and $inSSL ) {
  17. $destURL = str_replace('https:','http:', Director::absoluteURL($_SERVER['REQUEST_URI']));
  18. }
  19.  
  20. if( $destURL ) {
  21. header("Location: $destURL", true, 301);
  22. die('<h1>Your browser is not accepting header redirects</h1><p>Please <a href="'.$destURL.'">click here</a>');
  23. }
  24. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: dalethedeveloper on January 27, 2010

Also forgot the basic usage in a controller. Add the $ssl_actions static with an array of specific actions that need SSL:

public static $ssl_actions = array('shop','checkout','FormSignUp');

You need to login to post a comment.