Backend Development 3 min read

PHP pathinfo() Function: Syntax, Parameters, Return Values, and Practical Examples

This article explains PHP’s pathinfo() function, detailing its syntax, optional parameters, the structure of its return values, and provides two concrete code examples that demonstrate extracting directory name, base name, extension, and filename from file paths.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP pathinfo() Function: Syntax, Parameters, Return Values, and Practical Examples

The pathinfo() function in PHP returns information about a file path, such as directory name, base name, extension, and filename, either as an associative array or a string depending on the options supplied.

Its signature is mixed pathinfo(string $path[, int $options = PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME]) . If no $options are provided, the function returns an array containing dirname , basename , extension (if present), and filename .

The $path parameter specifies the file path to be parsed. The optional $options argument can be any combination of the constants PATHINFO_DIRNAME , PATHINFO_BASENAME , PATHINFO_EXTENSION , and PATHINFO_FILENAME to retrieve specific elements.

Example 1 demonstrates extracting each component from the path /www/htdocs/inc/lib.inc.php :

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
?>

Output:

/www/htdocs/inc
lib.inc.php
php
lib

Example 2 shows behavior when the path has an empty or missing extension:

<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);
$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>

Output:

string(0) ""
Notice: Undefined index: extension in test.php on line 6
NULL

These examples illustrate how pathinfo() can be used to reliably dissect file paths in PHP scripts.

BackendPHPphp-functionsfile pathPathInfo
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.