pathinfo function is used to return information about a given path. It accepts a file path as an argument and returns an array containing details about the path. This array provides the directory path, filename, and file extension, among other information.
pathinfo(string $path): array
$path: The input path, which can be either an absolute or relative file path.
This function returns an associative array containing the following keys:
'dirname': The directory part of the path.
'basename': The filename (including the extension).
'extension': The file extension.
'filename': The filename without the extension.
The pathinfo function returns an associative array with four key-value pairs. Here is a detailed explanation of each key:
Meaning: The directory part of the file, which is the location where the file is stored in the system.
Example:
Given the path /var/www/html/index.php, dirname returns /var/www/html.
Meaning: The filename, including its extension.
Example:
Given the path /var/www/html/index.php, basename returns index.php.
Meaning: The file extension, containing only the suffix after the filename.
Example:
Given the path /var/www/html/index.php, extension returns php.
Meaning: The filename part, without the extension.
Example:
Given the path /var/www/html/index.php, filename returns index.
<?php
$filePath = '/var/www/html/index.php';
<p>// Get path information<br>
$pathInfo = pathinfo($filePath);</p>
<p>// Output results<br>
echo 'Directory path: ' . $pathInfo['dirname'] . PHP_EOL;<br>
echo 'Filename: ' . $pathInfo['basename'] . PHP_EOL;<br>
echo 'Extension: ' . $pathInfo['extension'] . PHP_EOL;<br>
echo 'Filename (without extension): ' . $pathInfo['filename'] . PHP_EOL;<br>
?><br>
Output:
Directory path: /var/www/html
Filename: index.php
Extension: php
Filename (without extension): index
In some cases, we may need to pass a URL path to the pathinfo function to parse the filename or extension in the URL. Note that pathinfo can only parse file paths, so we need to extract the path part from the URL when using it.
For example, suppose you have the following URL:
$url = "https://www.gitbox.net/images/logo.png";
$parsedUrl = parse_url($url);
$pathInfo = pathinfo($parsedUrl['path']);
<p>// Output results<br>
echo 'Filename: ' . $pathInfo['basename'] . PHP_EOL;<br>
echo 'Extension: ' . $pathInfo['extension'] . PHP_EOL;<br>
Output:
Filename: logo.png
Extension: png
File Upload Handling: During file uploads, you can use pathinfo to get the uploaded file's filename and extension, for validation or processing.
Path Operations: When handling dynamically generated file paths, pathinfo can help developers break down the path and extract necessary parts.
URL Parsing: When you need to extract the filename or extension from a URL, combining parse_url and pathinfo can easily get you the information.