PHP - File paths

By xngo on September 23, 2019

PHP provides different functions and constants to get the file path or directory. Knowing the differences between them will make your life easier when using include_once() and require_once().

getcwd()

getcwd() function will return the directory path of where the php file is being executed.

From the command line, if you execute from /tmp directory, the output will look like the followings:

/tmp>php -f /var/www/html/path-examples.php 
/tmp

From the browser, if you open http://localhost/path-examples.php, he output will look like the followings:

/var/www/html

__FILE__

__FILE__ will return the path of the PHP file.

From the command line, if you execute from /tmp directory, the output will look like the followings:

/tmp>php -f /var/www/html/path-examples.php 
/var/www/html/path-examples.php

From the browser, if you open http://localhost/path-examples.php, the output will look like the followings:

/var/www/html/path-examples.php

__DIR__

__DIR__ will return the directory path of the PHP file.

From the command line, if you execute from /tmp directory, the output will look like the followings:

/tmp>php -f /var/www/html/path-examples.php 
/var/www/html

From the browser, if you open http://localhost/path-examples.php, the output will look like the followings:

/var/www/html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.