It’s easy to get the filename and directory name components of a full path name with PHP using the dirname(), basename() and pathinfo() functions. The latter also contains the filename extension.
Example full file path
The full file path used in these examples is:
$path = "/var/www/mywebsite/htdocs/images/myphoto.jpg";
Get the directory name with dirname()
PHP’s dirname() function returns just the directory part of the full path. This is done by simply excluding the last section of the full path based on the directory separator (/ on *nix based filesystems and on Windows) and no check is done to see if it’s actually a directory.
Note that both of the following:
echo dirname("/var/www/mywebsite/htdocs/images/"); echo dirname("/var/www/mywebsite/htdocs/images");
Get the filename with basename()
To just get the filename part of the full path use the basename() function. Note again it’s just the last part of the path that is considered to be the filename and no testing is done to see if it’s actually a file.
Get the directory name, filename and extension with pathinfo()
PHP’s pathinfo() function returns an associative array containing the basename, dirname, extension and (from PHP 5.2.0) the filename without the extension.
Array ( [dirname] => /var/www/mywebsite/htdocs/images [basename] => myphoto.jpg [extension] => jpg [filename] => myphoto )