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.
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.
// 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>
Running the above code will produce:
Directory: /home/user/www
Filename: example.php
Extension: php
Filename (without extension): example
Mastering pathinfo() can significantly improve efficiency and accuracy when working with file paths.