简体   繁体   中英

Get localhost project name from url

If I have a url like http://localhost/project1/ How am I able to get the project1 name from url

What I am trying to achieve is if is localhost $_SERVER['HTTP_HOST'] . '/' . $project $_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'] . '/';
} 

You can retrieve the parts of an URL with the parse_url() function:

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

Output:

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

Or, if you want to get the path directly:

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

You can access the requested URI with $_SERVER['REQUEST_URI']

So to get the project name in your URL you could do :

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

To get the the full host or your project you could do :

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

Better way if you have more than one sub directories:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM