如何获得网站的根网址? [英] How do I get the root url of the site?

查看:186
本文介绍了如何获得网站的根网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个琐碎的问题,但我正在寻找一种方法来获取网站网址的根目录,例如:http://localhost/some/folder/containing/something/here/or/there应该返回http://localhost/

Might be a trivial question, but I am looking for a way to say get the root of a site url, for example: http://localhost/some/folder/containing/something/here/or/there should return http://localhost/

我知道有$_SERVER['DOCUMENT_ROOT'],但这不是我想要的.

I know there is $_SERVER['DOCUMENT_ROOT'] but that's not what I want.

我确信这很容易,但是我一直在阅读:这篇文章试图弄清楚我应该使用或调用的内容.

I am sure this is easy, but I have been reading: This post trying to figure out what i should use or call.

想法?

与这个问题有关的另一个问题是-答案是否会在http://subsite.localhost/some/folder/containing/something/here/or/there这样的网站上起作用,所以我的最终结果是http://subsite.localhost/

The other question I have, which is in relation to this one is - will what ever the answer be, work on sites like http://subsite.localhost/some/folder/containing/something/here/or/there so my end result is http://subsite.localhost/

推荐答案

$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

如果您对当前脚本的方案和主机感兴趣.

If you're interested in the current script's scheme and host.

否则,如已经建议的那样,使用parse_url().例如

Otherwise, parse_url(), as already suggested. e.g.

$parsedUrl = parse_url('http://localhost/some/folder/containing/something/here/or/there');
$root = $parsedUrl['scheme'] . '://' . $parsedUrl['host'] . '/';

如果您还对路径之前的其他URL组件(例如凭据)感兴趣,还可以在完整的URL上使用strstr(),以路径"作为标记,例如

If you're also interested in other URL components prior to the path (e.g. credentials), you could also use strstr() on the full URL, with the "path" as the needle, e.g.

$url = 'http://user:pass@localhost:80/some/folder/containing/something/here/or/there';
$parsedUrl = parse_url($url);
$root = strstr($url, $parsedUrl['path'], true) . '/';//gives 'http://user:pass@localhost:80/'

这篇关于如何获得网站的根网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆