PHP: Getting Directory Path and Filename from A Full Path or URL

by Yang Yang on April 22, 2009

in PHP Tips & Tutorials

Share This Article:
Subscribe to Kavoir: blog feed

It’s common tasks to parse and deal with file paths or URL in PHP. And most common must be to identify and distinguish the directory path or file name from the file path or URL. For instance, the full path to a text file is: ‘/home/john/lanning.com/somefile.txt’ and you want get the directory part as well as file name parts separately from the entire path string.

This is how you do it:

$full_path = '/home/john/lanning.com/somefile.txt';
$file = basename($full_path);  // $file is "somefile.txt"
$dir  = dirname($full_path);   // $dir is "/home/john/lanning.com"

Yep, just use php function basename() to get the file name from a path and dirname() function to get the directory part of the path.

You can do the same with these 2 functions on URLs.

Another way to do this is to use pathinfo() function:

$info = pathinfo('/home/john/lanning.com/somefile.txt');
// $info['dirname'] is "/home/john/lanning.com"
// $info['basename'] is "somefile.txt"
// $info['extension'] is "txt"
Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 2 comments… read them below or add one }

Alexander September 7, 2010 at 8:24 am

Keep in mind that basefile doesn’t work with filenames containing letters in languages, other that English e.g. Russian.
‘Текстовая Картинка.jpg’ (‘Test Picture.jpg’) becomes ‘ Картинка.jpg’ (‘ Picture.jpg’)
This is a known php bug.
The only workaround is to transliterate filename, or do not use this function.

Reply

Yang Yang September 7, 2010 at 8:37 am

Thanks, Alex. That’s a rather helpful tip!

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: