00 Votes

PHP: Split File Path into Components - Path, Filename and Extension

Question by Compi | 2015-07-07 at 16:52

Does PHP offer any function making it possible to split a given file path like "/www/htdocs/file.txt" into its components such as file path "/www/htdocs/", file name "file" and file extension "txt"?

I know, that I can also achieve that by using several PHP functions such as substr, explode, implode and split, but I prefer a simple solution - if there is anyone available.

ReplyPositiveNegative
0Best Answer0 Votes

You can just use the PHP function pathinfo() and pass your file path to it. With this, you get an array containing all components of the file path. Here is an example of how to call pathinfo() and how to read out the information.

$pi = pathinfo('/www/htdocs/file.txt');

$pi['dirname'];   // /www/htdocs/inc
$pi['basename'];  // file.txt
$pi['extension']; // txt
$pi['filename'];  // file

If you do not need all of this information, you can also pass one of the constants PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME as a second parameter to the function in order to extract only this component. You can find an example for this in the topic about how to extract a file extension using PHP.

If you need more information about the file, you can also use SplFileInfo

Here is an example:

$finfo = new SplFileInfo('/www/htdocs/file.txt');

$path  = $finfo->getPath();       // /www/htdocs/inc
$bname = $finfo->getBasename();   // file.txt
$ext   = $finfo->getExtension();  // txt
$size  = $finfo->getSize();       // Integer Number

Otherwise, there are also available isDir, isFile, isReadable, isWritable etc.
2015-07-07 at 18:48

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.