Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

php - How do I get the root url of the site?

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/

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.

Ideas?

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$root = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';

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

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'] . '/';

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/'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...