The pathinfo Function

The pathinfo function returns an array with information about a file path. We pass a string with the path as the first parameter, and a flag as the second parameter, indicating which specific path component to return.

Syntax

phppathinfo(string $path, int $flags = PATHINFO_ALL);

Flags

Flag Description Returned Element
PATHINFO_DIRNAME Returns only the file directory dirname
PATHINFO_BASENAME Returns only the filename (with extension) basename
PATHINFO_EXTENSION Returns only the file extension extension
PATHINFO_FILENAME Returns only the filename (without extension) filename

Example

Get all information about the path:

php<?php
  $res = pathinfo('/var/www/index.php');
  print_r($res);
?>

Code execution result:

php[
  'dirname' => '/var/www',
  'basename' => 'index.php',
  'extension' => 'php',
  'filename' => 'index'
]

Example

Get only the filename:

php<?php
  echo pathinfo('/var/www/index.php', PATHINFO_FILENAME);
?>

Code execution result:

php'index'

Example

Get only the file extension:

php<?php
  echo pathinfo('/var/www/index.php', PATHINFO_EXTENSION);
?>

Code execution result:

php'php'

Example

Get only the filename with extension:

php<?php
  echo pathinfo('/var/www/index.php', PATHINFO_BASENAME);
?>

Code execution result:

php'index.php'

Example

Get only the directory:

php<?php
  echo pathinfo('/var/www/index.php', PATHINFO_DIRNAME);
?>

Code execution result:

php'/var/www'

See Also

  • the realpath function,
    which returns the absolute path
  • the basename function,
    which returns the filename
  • the dirname function,
    which returns the directory name