Content · Programming · PHP

PHP dirname() Function: Usage and Examples

Learn how PHP dirname works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

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

FunctionPurpose
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

MistakeCorrect Approach
Ignoring this behavior: The path is parsed as a string and does not need to existThe 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.

Share this resourceSend this page to someone who may find it useful.