PHP pathinfo

Created with Sketch.

PHP pathinfo

Summary: in this tutorial, you will learn how to use the PHP pathinfo() function to get the information on a file path.

Introduction to the PHP pathinfo() function

The PHP pathinfo() function accepts a file path and returns its components:

pathinfo ( string $path , int $flags = PATHINFO_ALL ) : array|string

Code language: PHP (php)

The pathinfo() function has two parameters:

  • $path is the file path from which you want to get the information.
  • $flags parameter specifies the part element to return.

The following table shows the valid flag values:

FlagMeaning
PATHINFO_DIRNAMEReturn the directory name
PATHINFO_BASENAMEReturn the base name
PATHINFO_EXTENSIONReturn the file extension
PATHINFO_FILENAMEReturn the file name (without the extension)

If you don’t pass the $flag argument, the pathinfo() function will return all components of a file path.

PHP pathinfo() function examples

Let’s take some examples of using the pathinfo() function.

1) Using the pathinfo() function to get all components of a file path

The following example uses the pathinfo() function to get the components of a file path:

<?php

$path = 'htdocs/phptutorial/index.php';

$parts = pathinfo($path);

print_r($parts);

Code language: HTML, XML (xml)

Output:

Array
(
[dirname] => htdocs/phptutorial
[basename] => index.php
[extension] => php
[filename] => index
)

Code language: PHP (php)

2) Using the pathinfo() function to get only a specific component of a file path

The following example uses the pathinfo() function get the basename of a file path:

<?php

$path = 'htdocs/phptutorial/index.php';

$basename = pathinfo($path, PATHINFO_BASENAME);

echo $basename;

Code language: HTML, XML (xml)

Output:

index.php

Code language: CSS (css)

3) Using the pathinfo() function to get the path components of a dot-file path

The following example uses the pathinfo() function to get components of the path of a dot-file:

<?php

$path = '/htdocs/phptutorial/.gitignore';

$parts = pathinfo($path);

print_r($parts);

Code language: HTML, XML (xml)

Output:

Array
(
[dirname] => /htdocs/phptutorial
[basename] => .gitignore
[extension] => gitignore
[filename] =>
)

Code language: PHP (php)

Summary

  • Use the PHP pathinfo() function to get the components of a file path including dirname, basename, filename, and extesion.

Leave a Reply

Your email address will not be published. Required fields are marked *