Reputation: 68650
code:
$url = 'https://www.example.com/path/to/product/filename.html';
echo parse_url($url);
output:
[scheme] => https
[host] => www.example.com
[path] => /path/to/product/filename.html
How do I get the current base path, that is:
https://www.example.com/path/to/product/
Upvotes: 0
Views: 2605
Reputation: 16117
You can use pathinfo()
<?php
$url = 'https://www.example.com/path/to/product/filename.html';
echo "<pre>";
print_r(pathinfo($url));
?>
Result:
Array
(
[dirname] => https://www.example.com/path/to/product
[basename] => filename.html
[extension] => html
[filename] => filename
)
You can get the path as:
<?php
$url = 'https://www.example.com/path/to/product/filename.html';
$info = pathinfo($url);
echo $info['dirname']; //https://www.example.com/path/to/product
?>
Upvotes: 2
Reputation: 600
You can use this function:
/**
* 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']."/";
}
or easier with this:
echo "http://".dirname($_SERVER['SERVER_NAME']."".$_SERVER['PHP_SELF']);
Upvotes: 0
Reputation: 164736
Easy
$basePath = dirname($url) . '/';
Demo ~ https://3v4l.org/XGNDd
Upvotes: 3