Jigar KarangiyaJigar Karangiya

How to get current file directory in PHP?

JK
Jigar Karangiya
· 1 min read
How to get current file directory in PHP?

In this article i will introduce a few methods to get the current working directory name in PHP.

1. Use the getcwd() Function to Get the Current Directory Name in PHP

The getcwd() function gives the current working directory. The returned value is a string on success. The function does not take any parameters. The function returns false in case of failure.

2. Use the dirname() Function to Get the Current Directory Name in PHP

We can also use the dirname() function to get the current directory name in PHP. The function returns the path of the parent directory. It accepts two parameters where the first one is the path and the second one is levels. Levels indicate the number of directories to move up. Finally, we can use the __FILE__ magic constants in the dirname() function to get the name of the current directory. The __FILE__ constant returns the full path of the current file along with the file name.

php
<?php
 
echo getcwd();
//returns the current working directory with its path. 
//OUTPUT : /var/www/html/project
 
echo __FILE__;
//echo the __FILE__ constant from the file. 
//OUTPUT : /var/www/html/project/index.php
 
echo __DIR__; 
//returns current working directory 
 
echo dirname(__FILE__); 
//get the current working directory name in PHP 
//OUTPUT : /var/www/html/project
 
echo realpath(__DIR__); 
//returns canonicalized absolute pathname
 

I hope this tutorial was helpful in understanding various methods of working with directories in PHP. Thanks !!

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts