I need to force all requests as HTTPS in my multimodule application. I've found a topic on Phalcon forum about this but it doesn't give the answer.
My problems:
(1) How to build a new, valid URL/request based on the current?
My solution:
if(!$di->get('request')->isSecureRequest()){
$url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$di->get('response')->redirect($url);
return false;
}
Do you know any other better solutions? Is there a solution to produce a new, little changed URL based on the matched route?
(2) Where to put this?
First (check post in the linked topic) I have put the code in the base controller -> in the beforeExecuteRoute
method. I have a multimodule application so I decided to change it. At the end I've put the code in the index.php bootstrap -> dispatcher -> event. Check the full code below!
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
//Create an event manager
$eventsManager = new EventsManager();
//Attach a listener for type "dispatch"
$eventsManager->attach("dispatch:beforeDispatchLoop", function($event, $dispatcher) {
$di = $dispatcher->getDI();
if(!$di->get('request')->isSecureRequest()){
$url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$di->get('response')->redirect($url);
return false;
}
return true;
});
//Bind the eventsManager to the view component
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
},true);
What do you think? Is there a better place to put this than in dispatcher event?
(3) How to handle requests other than GET e.g. POST?
At the moment I don't need it but probably I will. I am thinking how to handle full request, I mean POST data, ports etc.? Is there a "sexy" soluton for these?
(4) Other ways?
I have heard that other solution is to change some settings in apache. Did you heard about it? Any other solutions? What are pros and cons?
Every input is highly appreciated!. TIA