VOOZH about

URL: https://www.geeksforgeeks.org/php/php-pathinfo-function/

⇱ PHP | pathinfo( ) Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP | pathinfo( ) Function

Last Updated : 11 Jul, 2025

The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string. 
The returned array or string contains the following information: 
 

  • Directory name
  • Basename
  • Extension


The path and options are sent as a parameters to the pathinfo() function and it returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Syntax:  

pathinfo(path, options)


Parameters Used: 
The pathinfo() function in PHP accepts two parameters.  

  1. path : It is a mandatory parameter which specifies the path of the file.
  2. options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. 
    Possible values can be restricted using : 
    • PATHINFO_DIRNAME - return only dirname
    • PATHINFO_BASENAME - return only basename
    • PATHINFO_EXTENSION - return only extension


Return Value: 
It returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Errors And Exceptions:  

  1. PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension.
  2. No extension element is returned, if the path does not have an extension.
  3. If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty.


Examples: 

Input : print_r(pathinfo("/documents/gfg.txt"));
Output : Array
 (
 [dirname] => /documents
 [basename] => gfg.txt
 [extension] => txt
 )

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_DIRNAME));
Output : /documents

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_EXTENSION));
Output : txt

Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_BASENAME));
Output : gfg.txt


Below programs illustrate the pathinfo() function.
Suppose there is a file named "gfg.txt"
Program 1

Output:  

 Array
 (
 [dirname] => /documents
 [basename] => gfg.txt
 [extension] => txt
 )


Program 2

Output:  

 /documents 


Program 3

Output:  

 txt 


Program 4

Output:  

 gfg.txt 


Reference: 
https://www.php.net/manual/en/function.pathinfo.php 

Comment