• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Get the directory name and filename from a full path name with PHP

Get the directory name and filename from a full path name with PHP

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.

echo dirname($path)

will echo

/var/www/mywebsite/htdocs/images

Note that both of the following:

echo dirname("/var/www/mywebsite/htdocs/images/");
echo dirname("/var/www/mywebsite/htdocs/images");

will echo

/var/www/mywebsite/htdocs

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.

echo basename($path);

will echo

myphoto.jpg

and

echo basename("/var/www/mywebsite/htdocs/images");

would echo

images

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.

print_r(pathinfo($path));

will echo

Array
(
    [dirname] => /var/www/mywebsite/htdocs/images
    [basename] => myphoto.jpg
    [extension] => jpg
    [filename] => myphoto
)

Check Out These Related posts:

  1. Generate thumbnails with PHP
  2. Which directory is that bash script in?
  3. Extract domain, path etc from a full url with PHP
  4. Get the current page path and filename with Javascript

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap