PHP: Get Base (Directory) From File (URL, Path)

Posted on September 7, 2008, under PHP,  Bookmark it

If you need to determine the base element from a URL or path of a file then this snippet can help you.

<?php
/*
Source: http://www.bitrepository.com/
*/
function Get_Base_From_File($file)
{
$find = '/';

$after_find = substr(strrchr($file, $find), 1);

$strlen_str = strlen($after_find);

$result = substr($file, 0, -$strlen_str);

return $result;
}

$file = 'http://www.domain.com/path/to/file.zip';

$base = Get_Base_From_File($file);

// Output: http://www.domain.com/path/to/
echo $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!

2 Replies to "PHP: Get Base (Directory) From File (URL, Path)"

  1. thanks! looking for this!

  2. it doesn’t work if the base URL doesnt have trailing slash,

    like http://domain.com

    returns htp://

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