php Laravel 5 如何获取 HTTP 主机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39835650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:00:50  来源:igfitidea点击:

How do you get the HTTP host with Laravel 5

phplaravelhttplaravel-5

提问by Sean the Bean

I'm trying to get the hostname from an HTTP request using Laravel 5, including the subdomain (e.g., dev.site.com). I can't find anything about this in the docs, but I would think that should be pretty simple. Anyone know how to do this?

我正在尝试使用 Laravel 5 从 HTTP 请求中获取主机名,包括子域(例如,dev.site.com)。我在文档中找不到任何关于此的信息,但我认为这应该很简单。有人知道怎么做吗?

回答by Sean the Bean

Good news! It turns out this is actually pretty easy, although Laravel's Request documentation is a bit lacking (the method I wanted is inherited from Symfony's Requestclass). If you're in a controller method, you can inject the request object, which has a getHttpHostmethod. This provides exactly what I was looking for:

好消息!事实证明这实际上很容易,虽然 Laravel 的 Request 文档有点缺乏(我想要的方法是从Symfony 的Request继承)。如果您在控制器方法中,则可以注入具有getHttpHost方法的请求对象。这正是我正在寻找的:

public function anyMyRoute(Request $request) {
    $host = $request->getHttpHost(); // returns dev.site.com
}

From anywhere else in your code, you can still access the request object using the requesthelper function, so this would look like:

从代码中的任何其他地方,您仍然可以使用requesthelper 函数访问请求对象,所以这看起来像:

$host = request()->getHttpHost(); // returns dev.site.com

If you want to include the http/https part of the URL, you can just use the getSchemeAndHttpHostmethod instead:

如果要包含 URL 的 http/https 部分,则可以改用该getSchemeAndHttpHost方法:

$host = $request->getSchemeAndHttpHost(); // returns https://dev.site.com

It took a bit of digging through the source to find this, so I hope it helps!

花了一些时间挖掘源代码才找到这个,所以我希望它有所帮助!

回答by insign

There two ways, so be careful:

有两种方法,所以要小心:

<?php

    $host = request()->getHttpHost(); // With port if there is. Eg: mydomain.com:81

    $host = request()->getHost(); // Only hostname Eg: mydomain.com

回答by chebaby

laravel 5.6 and above

Laravel 5.6 及以上

request()->getSchemeAndHttpHost()

Example of use in blade :

在刀片中的使用示例:

{{ request()->getSchemeAndHttpHost() }}

回答by Vivek Pandey

You can use request()->url();

您可以使用 request()->url();

Also you can dump the complete request()->headers();

你也可以转储完整的 request()->headers();

And see if that data is useful for you.

看看这些数据是否对你有用。