Get Root Directory Path of a PHP project?

In PHP, you can get the root directory path of your project using built-in constants and functions. The most common approaches are using __DIR__ or dirname(__FILE__).

Using __DIR__ Constant

The __DIR__ constant returns the directory path of the current file −

<?php
    echo __DIR__;
?>

Using dirname(__FILE__)

The dirname(__FILE__) function achieves the same result −

<?php
    echo dirname(__FILE__);
?>

Comparison Example

Here's both methods demonstrated together −

<?php
    echo "Using dirname(__FILE__): " . dirname(__FILE__);
    echo "<br>";
    echo "Using __DIR__: " . __DIR__;
?>
Using dirname(__FILE__): /home/KOq8Zd
Using __DIR__: /home/KOq8Zd

Getting Project Root Directory

To get the actual project root (not just current file's directory), you might need to navigate up directories −

<?php
    // Get current directory
    echo "Current directory: " . __DIR__ . "<br>";
    
    // Get parent directory
    echo "Parent directory: " . dirname(__DIR__) . "<br>";
    
    // Get two levels up
    echo "Two levels up: " . dirname(__DIR__, 2) . "<br>";
?>
Current directory: /home/KOq8Zd
Parent directory: /home
Two levels up: /

Conclusion

__DIR__ is the modern preferred method over dirname(__FILE__). Use dirname(__DIR__, levels) to navigate up directory levels when needed for project root access.

Updated on: 2026-03-15T09:28:34+05:30

23K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements