Course Content
State Management
0/1
Regular Expressions?
0/1
About Lesson

What is pathinfo() function?

In PHP, the pathinfo() function is used to retrieve information about a file path. It returns an associative array containing information such as the directory name, basename, extension, and filename without extension.

Syntax:

array pathinfo ( string $path [, int $options = PATHINFO_ALL ] )

  • $path: Specifies the file path for which you want to retrieve information.
  • $options (optional): Specifies the information to be returned. It can be one of the following constants:
  • PATHINFO_DIRNAME: Returns the directory name.
  • PATHINFO_BASENAME: Returns the basename of the file.
  • PATHINFO_EXTENSION: Returns the file extension.
  • PATHINFO_FILENAME: Returns the filename without the extension.
  • PATHINFO_ALL: Returns an associative array containing all of the above components (default).

Example:

PHP
<?php

$path = '/path/to/some/file.txt';

$pathInfo = pathinfo($path);

echo "Directory: " . $pathInfo['dirname'] . "n";

echo "Basename: " . $pathInfo['basename'] . "n";

echo "Extension: " . $pathInfo['extension'] . "n";

echo "Filename: " . $pathInfo['filename'] . "n";

?>

Output:

Directory: /path/to/some

Basename: file.txt

Extension: txt

Filename: file

Use Cases:

  • It’s useful for extracting various components of a file path, such as the directory, basename, extension, or filename without extension.
  • It simplifies file path parsing and manipulation tasks, allowing you to work with file paths more efficiently.

The pathinfo() function provides a convenient way to extract file path information in PHP, making it easier to work with files and directories in your applications.