SilverStripe SSL switching by statics


/ Published in: PHP
Save to your folder(s)

A little function I add to the base Page_Controller 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 Page_Controller.

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.