How do I get the root url of the site?

前端 未结 5 1504
时光说笑
时光说笑 2020-12-05 13:20

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

5条回答
  •  天命终不由人
    2020-12-05 14:14

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

提交回复
热议问题