» Birthday Bundle - Over $400 worth of Envato files for just $20

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!

Get our RSS Feed!

Related Posts

4 Replies to "PHP: Get Main Base URL"

  1. usefull example. thax bro

  2. instead u can use basename($_SERVER['PHP_SELF']);

  3. $_SERVER['PHP_SELF'] only

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)