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"


Facebook
Twitter
Google Plus
{ 2 comments… read them below or add one }
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.
Thanks, Alex. That’s a rather helpful tip!
{ 1 trackback }