如何从 laravel HTTP 请求类获取传入请求的协议(http/https)



在我的新应用程序API中,我必须检查来自第三方URL的请求是否应该在https中。如果不是https,我必须返回消息为"连接不安全"。谁能帮我?

你在这里:

Determining If The Request Is Over HTTPS
Using Request::secure()
if (request()->secure())
{
  //
}

如果您的主机位于负载均衡器后面,请改用请求 getScheme

Daniel Tran的回答是正确的,只是为了提供信息HTTPS类型请求在请求上有一个额外的字段HTTPS。有时这个字段也可以等于 off,但不能等于别的。

所以你可以写一个代码,

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

拉维尔请求类也从交响乐中继承了完全不同的东西。您可以在下面找到;

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);
    }

来自 Laravel 请求类 使用getSchemeAndHttpHost()方法

{{ Request::getSchemeAndHttpHost() }}

返回例如:

  • http://example.com

  • http://192.0.0.1

  • https://example.com

返回protocol/domain名称

Request::getScheme()

返回"http"或https">

如果要获取协议字符串。