从url获取localhost项目名称

时间:2015-05-04 00:36:49

标签: php codeigniter

如果我有一个像http://localhost/project1/这样的网址我怎样才能从网址获取project1名称

我想要实现的是if localhost $_SERVER['HTTP_HOST'] . '/' . $project

if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
echo 'https://' . $_SERVER['HTTP_HOST'];
} elseif ($_SERVER['HTTP_HOST'] == 'localhost') {
echo 'http://' . $_SERVER['HTTP_HOST'] . '/'; // GET PROJECT NAME Place after .'/'.
} else {
echo 'http://' . $_SERVER['HTTP_HOST'] . '/';
} 

3 个答案:

答案 0 :(得分:3)

您可以使用parse_url()功能检索网址的各个部分:

$url = 'http://localhost/project1/';
$parts = parse_url($url);
print_r($parts);

输出:

Array
(
    [scheme] => http
    [host] => localhost
    [path] => /project1/
)

或者,如果您想直接获取路径:

$path = parse_url($url, PHP_URL_PATH);
// => /project1/

答案 1 :(得分:3)

您可以使用$_SERVER['REQUEST_URI']

访问请求的URI

所以要在你的URL中获取项目名称,你可以这样做:

$project = explode('/', $_SERVER['REQUEST_URI'])[1];

要获得完整的主机或项目,您可以这样做:

function getFullHost()
{
    $protocole = $_SERVER['REQUEST_SCHEME'].'://';
    $host = $_SERVER['HTTP_HOST'] . '/';
    $project = explode('/', $_SERVER['REQUEST_URI'])[1];
    return $protocole . $host . $project;
}

答案 2 :(得分:0)

如果您有多个子目录,则更好:

function getFullHost()
{
    $protocole = $_SERVER['REQUEST_SCHEME'].'://';
    $host = $_SERVER['HTTP_HOST'] . '/';
    $project = explode('/', $_SERVER['REQUEST_URI']);
    array_pop($project);
    array_shift($project);
    $path = implode('/', $project);
    return $protocole . $host . $path;
}