Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get parent folder paths with php

I am working on my first MVC framework, and want to define 4 constants for BASE_PATH, APP_PATH, LIB_PATH & PUBLIC_PATH. My file structure looks like this:

/
/app
    /controllers
    /models
    /views
/config
/db
/lib
/public_html
    /css
    /js
    /img

My index.php file is located in the public_html directory. And currently has the following code:

error_reporting(E_ALL);
define('BASE_PATH',dirname(realpath(__FILE__)) . "/../");
define('APP_PATH',dirname(realpath(__FILE__)) . "/../app/");
define('LIB_PATH',dirname(realpath(__FILE__)) . "/../lib/");
define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");

require LIB_PATH . 'core.php';

This works, but I feel like there must be a better way of doing it without all of the "..". Any suggestions or is this the best way of going about it? Let me know. Thank you!


ANSWER

Thank you to @fireeyedboy and @KingCrunch, I have come up with the solution I was looking for. This is my final code:

define('PUBLIC_PATH', dirname(__FILE__) . "/");
define('BASE_PATH', dirname(PUBLIC_PATH) . "/");
define('APP_PATH', BASE_PATH . "app/");
define('LIB_PATH', BASE_PATH . "lib/");
like image 1000
Yev Avatar asked Apr 07 '11 14:04

Yev


People also ask

How do I get file path in php?

The realpath() function returns the absolute pathname. This function removes all symbolic links (like '/./', '/../' and extra '/') and returns the absolute pathname.

What is __ DIR __ in php?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

How do I go back to a parent directory in php?

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.

How do I reference a parent directory in path?

Using os.path.dirname() to get parent of current directory path.


2 Answers

How about this:

define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");
define('BASE_PATH',dirname(PUBLIC_PATH));
define('APP_PATH',BASE_PATH . "/app/");
define('LIB_PATH',BASE_PATH . "/lib/");

In other words use dirname() again. And re-order defining the constants to make direct use of them. Not sure it helps readability though.

like image 171
Decent Dabbler Avatar answered Oct 05 '22 23:10

Decent Dabbler


First:

realpath(__FILE__)

is just useless

However, there no "real" better way, because ../ is not "dirty". The only other solution, that comes in my mind

dirname(dirname(__FILE__))

.. is the way a filesystem (its not invented by php ;)) defines its parent directory, just as well . defines the current directory.

like image 26
KingCrunch Avatar answered Oct 05 '22 23:10

KingCrunch