Current Location: Home> Latest Articles> Comprehensive Guide to PHP pathinfo() Function: Easily Extract File Path Information

Comprehensive Guide to PHP pathinfo() Function: Easily Extract File Path Information

M66 2025-06-22

Introduction to PHP Function — pathinfo(): Returns File Information from a Path

In web development, handling file information is a common task, such as retrieving a file’s path, name, or extension. PHP’s built-in pathinfo() function greatly simplifies these operations by extracting useful file information from a full file path.

Syntax of pathinfo() Function

The basic usage of pathinfo() is as follows:

<span class="fun">pathinfo($path, $options);</span>

Here, $path is the file path, and $options is an optional parameter that specifies which information to return. The function returns an array containing various parts of the path.

Common Options Explained

  1. PATHINFO_DIRNAME: Returns the directory part of the path
  2. PATHINFO_BASENAME: Returns the filename part of the path (including extension)
  3. PATHINFO_EXTENSION: Returns the file extension part
  4. PATHINFO_FILENAME: Returns the filename without the extension

Example Code

// Get the directory part of the path
$path = "/home/user/www/example.php";
$dirname = pathinfo($path, PATHINFO_DIRNAME);
echo "Directory: " . $dirname . "\n";
<p>// Get the filename part of the path<br>
$basename = pathinfo($path, PATHINFO_BASENAME);<br>
echo "Filename: " . $basename . "\n";</p>
<p>// Get the file extension part<br>
$extension = pathinfo($path, PATHINFO_EXTENSION);<br>
echo "Extension: " . $extension . "\n";</p>
<p>// Get the filename without extension<br>
$filename = pathinfo($path, PATHINFO_FILENAME);<br>
echo "Filename (without extension): " . $filename . "\n";<br>

Output Result

Running the above code will produce:

Directory: /home/user/www
Filename: example.php
Extension: php
Filename (without extension): example

Summary

  • pathinfo() is a practical PHP function for handling file path information.
  • Using different options, you can get the directory, filename, extension, or filename without extension.
  • This function is commonly used in file uploads, file management, and other development scenarios.

Mastering pathinfo() can significantly improve efficiency and accuracy when working with file paths.