Sathishkumar R
Sathishkumar R

Reputation: 181

How to get protocol(http/https) of the incoming request from the laravel HTTP request class?

In my new application API, I have to check the request from the third party URL's should be in https. If it is not https, I have to return the message as "connection is not secure'. Can anyone help me?

Upvotes: 15

Views: 24643

Answers (4)

linus zhou
linus zhou

Reputation: 1

Request::getScheme()

return "http" or https"

if you want get the protocol string.

Upvotes: 0

Yogendra Tomar
Yogendra Tomar

Reputation: 121

From Laravel Request Class use getSchemeAndHttpHost() method

{{ Request::getSchemeAndHttpHost() }}

Returns for example :

  • http://example.com or

  • http://192.0.0.1 or

  • https://example.com

returns protocol/domain name

Upvotes: 2

Daniel Tran
Daniel Tran

Reputation: 6171

Here you are:

Determining If The Request Is Over HTTPS
Using Request::secure()

if (request()->secure())
{
  //
}

If your host are behind a load balancer, use Request getScheme instead

Upvotes: 31

Anar Bayramov
Anar Bayramov

Reputation: 11594

Daniel Tran's answer is correct just for information HTTPS type requests have an extra field HTTPS on requests. Sometimes this field can be equal to off too but nothing else.

so you can just write a code like

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { 
  doSomething();
}

Laravel Request Class also inherited something totally similar from symphony. Which You can find under;

vendor/symfony/http-foundatiton/Request.php

public function isSecure()
    {
        if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
            return in_array(strtolower(current(explode(',', $proto))), array('https', 'on', 'ssl', '1'));
        }

        $https = $this->server->get('HTTPS');

        return !empty($https) && 'off' !== strtolower($https);
    }

Upvotes: 3

Related Questions