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

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"

4 thoughts on “PHP: Getting Directory Path and Filename from A Full Path or URL”

  1. Pingback: PHP: Why you should use dirname(__FILE__).’/include.php’ instead of just ‘include.php’

  2. 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.

  3. I hate mis-information! The above does not work at all!

    I have a form and the $_POST[‘file’] contains the value of:

    /data/myfile.txt

    Using the previous information:

    $fname = $_POST[‘file’]; contains only “myfile.txt”

    nothing I do using anything from the previous information will give me the full path of the file.

    Please do not put up mis-information. None of the above works unless you hard code the file name, which nobody does, everyone gets it from a form!

    OMR

Comments are closed.

Scroll to Top