Request getScheme in Phalcon PHP 1.3.4 not working properly post

11/23/2014 with tags : php, phalcon

Phalcon PHP does not always correctly detect http shcema. Inside a controller class we can get current schema by calling 1

 $this->request->getScheme()

Looking at the code we can see that this method is simply checking for HTTPS key in _SERVER superglobal.

This works fine for most cases, but failes for servers behind a load balancer. In that case HTTPS key is not set.

After some digging I found this awsome answer on stackoverflow. It says that for server behind load balancers schema should be validated against server property named HTTP_X_FORWARDED_PROTO.

Easiest solution is to override getSchema method

class Request extends \Phalcon\Http\Request {

    public function getScheme()
    {
        $isSecure = false;
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $isSecure = true;
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
            $isSecure = true;
        }
        return $isSecure ? 'https' : 'http';
    }

}

And use this class in DI as a default request service.


  1. $this refers is an instance of \Phalcon\Mvc\Controller