Returns a parent directory component from a path string.
What Is dirname() in PHP?
Returns a parent directory component from a path string.
Its syntax is:
dirname(string $path, int $levels = 1): string
Parameters:
$path— Accepted as string; required argument.$levels— Accepted as int; optional default 1.
Return type: string. The path is parsed as a string and does not need to exist. Directory separators differ by platform.
Availability: Core PHP.
Example 1: Basic Usage
<?php
echo dirname("/var/log/app.log");
Output:
/var/log
The path is parsed as a string and does not need to exist. Directory separators differ by platform.
Example 2: A Different Input
<?php
echo dirname("/var/www/site/index.php", 2);
Output:
/var/www
The path is parsed as a string and does not need to exist. Directory separators differ by platform.
Practical Example: Applying It in a Program
<?php
$filePath = "/var/www/site/uploads/photo.jpg"; $parentFolder = dirname($filePath); echo basename($parentFolder);
Output:
uploads
The path is parsed as a string and does not need to exist. Directory separators differ by platform.
Important Behavior and Edge Cases
- Key behavior: The path is parsed as a string and does not need to exist. Directory separators differ by platform.
- Environment: Core PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
dirname() | Returns a parent directory component from a path string. |
basename() | basename() returns the last path component; dirname() returns its parent directory. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The path is parsed as a string and does not need to exist | The path is parsed as a string and does not need to exist. Directory separators differ by platform. |
Key Takeaways
- Returns a parent directory component from a path string.
- The path is parsed as a string and does not need to exist. Directory separators differ by platform.
- Core PHP.
Summary: The path is parsed as a string and does not need to exist. Directory separators differ by platform.