PHP: Get Main Base URL
Posted on September 8, 2008, Filled under PHP,
Bookmark it
This is a snippet which extracts the Main Base Address from a complete URL:
<?php
function GetMainBaseFromURL($url)
{
$chars = preg_split('//', $url, -1, PREG_SPLIT_NO_EMPTY);
$slash = 3; // 3rd slash
$i = 0;
foreach($chars as $key => $char)
{
if($char == '/')
{
$j = $i++;
}
if($i == 3)
{
$pos = $key; break;
}
}
$main_base = substr($url, 0, $pos);
return $main_base.'/';
}
$url = 'http://mysubdomain.mydomain.com/category/hardware/subcategory/mainboards.html';
$main_base = GetMainBaseFromURL($url);
// Output: http://mysubdomain.mydomain.com/
echo $main_base;
?>
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- September 8, 2008
- article by Gabriel C.
- 4 comments
Related Posts
Create, Customize and Send Newsletters: MeeNewsat August 3, 2009 with 1 comment
PHP: Get Base (Directory) From File (URL, Path)at September 7, 2008 with 2 comments
Shorten a string (text)at September 3, 2008 with 2 comments
Free Open Source PHP MySQL Driven Knowledge Base Softwareat July 22, 2009

4 Replies to "PHP: Get Main Base URL"
February 9, 2009 at 1:11 PM
usefull example. thax bro
January 14, 2010 at 10:04 PM
Hi, I suggest you use parse_url function.
http://php.net/manual/en/function.parse-url.php
July 28, 2010 at 7:00 PM
instead u can use basename($_SERVER['PHP_SELF']);
July 28, 2010 at 7:04 PM
$_SERVER['PHP_SELF'] only