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

by Yang Yang on April 22, 2009

in PHP Tips & Tutorials

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"

Related Posts

Previous post:

Next post: