PHP Tutorial - PHP pathinfo() Function






Definition

The pathinfo() function returns an array that contains information about a path.

Syntax

PHP pathinfo() Function has the following syntax.

pathinfo(path,options)

Parameter

ParameterIs RequiredDescription
pathRequired.Path to check
optionsOptional.Which array elements to return. Default is all

Possible values for options:

  • PATHINFO_DIRNAME - return only dirname
  • PATHINFO_BASENAME - return only basename
  • PATHINFO_EXTENSION - return only extension




Return

If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.

Example

The pathinfo() function takes a filename as its only parameter and returns an array with three elements: dirname, basename, and extension.

Dirname contains the name of the directory the file is in, basename contains the base filename, and extension contains the file extension, if any (e.g., html or txt).

You can see this information yourself by running this script:


<?PHP
      $filename = "test.txt";
      $fileinfo = pathinfo($filename);
      var_dump($fileinfo);
      
      print_r(pathinfo("test.txt",PATHINFO_BASENAME));
?>

The code above generates the following result.





Example 2

The following code shows how to find out path information about dirname, basename, extension and filename.


<?php
    $pathinfo = pathinfo('c:/Java_Dev');
    printf("Dir name: %s <br />", $pathinfo['dirname']);
    printf("Base name: %s <br />", $pathinfo['basename']);
    printf("Extension: %s <br />", $pathinfo['extension']);
    printf("Filename: %s <br />", $pathinfo['filename']);
?>

The code above generates the following result.