breich

Force HTTPS with Zend Framework 2.0

Apr 1st, 2013
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Reich Consulting
  5.  *
  6.  * @author    Brian Reich <breich@reich-consulting.net>
  7.  * @copyright (C) 2013 Reich Consulting http://www.reich-consulting.net
  8.  * @version   1.0
  9.  */
  10.  
  11. namespace ForceHttps
  12. {
  13.     use Zend\ModuleManager\ModuleManager;
  14.     use Zend\Mvc\MvcEvent;
  15.    
  16.     /**
  17.      * ForceHttps Module for Zend Framework 2.0
  18.      *
  19.      * This is a drop-in module for Zend Framework 2.0 which forces all traffic
  20.      * through HTTPS. In order to use this module you need to copy this code to
  21.      * <project>/module/ForceHttps/Module.php, then add ''ForceHttps' to the
  22.      * modules config in application.config.php.
  23.      *
  24.      * @namespace ForceHttps
  25.      */
  26.     class Module
  27.     {
  28.         /**
  29.          * Adds listener to "route" event from Zend\Mvc\Application which
  30.          * forces communication through https.
  31.          *
  32.          * @param ModuleManager $moduleManager The ModuleManager
  33.          */
  34.         public function init(ModuleManager $moduleManager)
  35.         {
  36.             $moduleManager->getEventManager()->getSharedManager()->attach(
  37.                     'Zend\Mvc\Application', 'route',
  38.                     array($this, 'enforceHttps'), -10
  39.             );
  40.            
  41.         }
  42.        
  43.         /**
  44.          * Enforces https.
  45.          *
  46.          * @param MvcEvent $event The event generated from the request.
  47.          *
  48.          * @return \Zend\Http\Response Returns the modified response.
  49.          */
  50.         public function enforceHttps(MvcEvent $event)
  51.         {
  52.             // Get Request object and URI of request
  53.             $request = $event->getRequest();
  54.             $uri     = $request->getUri();
  55.            
  56.             // If scheme isn't https, change URI and redirect.
  57.             if( $uri->getScheme() !== 'https' )
  58.             {
  59.                 $uri->setScheme( 'https' );    // Change scheme to https
  60.                 $uri->setPort(null);           // Let server decide https port
  61.                
  62.                 $response = $event->getResponse();
  63.                 $response->getHeaders()->addHeaderLine('Location', $uri->__toString() );
  64.                
  65.                 return $response;
  66.             }
  67.            
  68.         }
  69.        
  70.     }    
  71. }
Add Comment
Please, Sign In to add comment