获取URL中的基本路径

时间:2016-10-21 06:07:24

标签: php

$url = 'https://www.example.com/path/to/product/filename.html';
echo parse_url($url);

输出

[scheme] => https
[host] => www.example.com
[path] => /path/to/product/filename.html

如何获取当前的基本路径,即:

https://www.example.com/path/to/product/

3 个答案:

答案 0 :(得分:2)

$basePath = dirname($url) . '/';

演示〜https://3v4l.org/XGNDd

答案 1 :(得分:2)

您可以使用pathinfo()

<?php
$url = 'https://www.example.com/path/to/product/filename.html';
echo "<pre>";
print_r(pathinfo($url));
?>

<强>结果:

Array
(
    [dirname] => https://www.example.com/path/to/product
    [basename] => filename.html
    [extension] => html
    [filename] => filename
)

您可以将路径视为:

<?php
$url = 'https://www.example.com/path/to/product/filename.html';
$info = pathinfo($url);
echo $info['dirname']; //https://www.example.com/path/to/product
?>

答案 2 :(得分:0)

您可以使用此功能:

/**
     * Suppose, you are browsing in your localhost 
     * http://localhost/myproject/index.php?id=8
     */
    function getBaseUrl() 
    {
        // output: /myproject/index.php
        $currentPath = $_SERVER['PHP_SELF']; 

        // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
        $pathInfo = pathinfo($currentPath); 

        // output: localhost
        $hostName = $_SERVER['HTTP_HOST']; 

        // output: http://
        $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';

        // return: http://localhost/myproject/
        return $protocol.$hostName.$pathInfo['dirname']."/";
    }

或更容易:

echo "http://".dirname($_SERVER['SERVER_NAME']."".$_SERVER['PHP_SELF']);