Force HTTPS?

So in an ordinary PHP application if I wanted to force https I would put in each page something like this:

if($_SERVER["HTTPS"] != "on")
{
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

But within the context of Phalcon is there some way to do this? Would I put that inside my dispatcher somewhere?

edited Jun '14

I don't think Phalcon has specific built-in functionality to provide this. One note though: $_SERVER["HTTPS"] won't even be set if the user is viewing via http, so you'll want to change your condition to:

if(!isset($_SERVER["HTTPS"]))

Do you have access to the server? On my servers, I have one host that answers to HTTP requests, and one that answers to HTTPS requests. I've just set up a redirect on the HTTP host to forward all requests to the HTTPS host. I think that could be done with an .htaccess file as well, which I feel would be best, as it doesn't require firing up PHP.

If you don't have access, just paste this in the top of your index.php file. One



9.2k
edited Jun '14

on the docs

$router->add('/login', array(
    'module' => 'admin',
    'controller' => 'session'
))->beforeMatch(function($uri, $route) {
    //Check if the request was made with Ajax
    if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') {
        return false;
    }
    return true;
});

you can implement the check.

like here http://stackoverflow.com/questions/1175096/how-to-find-out-if-you-are-using-https-without-serverhttps

Edit:

Phalcon use this:

    $request = new \Phalcon\Http\Request();

    var_dump($request->getScheme());


15.7k

@blm14 Hi! Did you solved your problem? ;> How your code looks like and where have you put it? I am having this problem now.



15.7k
edited Nov '14

I have a base controller that is parent class for other controllers it looks like this:

<?php

class ControllerBase extends \Phalcon\Mvc\Controller {

    public function beforeExecuteRoute() {

        /* 
         * Force HTTPS. 
         */
        if(!$this->request->isSecureRequest()){
            $url = "https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
            $this->response->redirect($url);
            return false;
        }
        return true;
    }   
}

What do you think? I was wondering if this is going to work if request is other then GET? I am worry that it will not work.

Why You are not use 301 redirect in http-server settings? (.htaccess for Apache)



15.7k

I have finally decided to make an server redirection in apache, as vitalikoziy suggested. Thanks @vitaliykoziy !

Full: http://forum.phalconphp.com/discussion/4055/how-to-force-https#C13651