Get parent folder paths with php

I am working on my first MVC base and want to define 4 constants for BASE_PATH, APP_PATH, LIB_PATH and PUBLIC_PATH. My file structure is as follows:

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

My index.php file is 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'; 

It works, but I feel that there should be a better way to do this without all the "..". Any suggestions or is this the best way around this? Let me know. Thanks!


ANSWER

Thanks @fireeyedboy and @KingCrunch, I came up with the solution I was looking for. This is my last code:

 define('PUBLIC_PATH', dirname(__FILE__) . "/"); define('BASE_PATH', dirname(PUBLIC_PATH) . "/"); define('APP_PATH', BASE_PATH . "app/"); define('LIB_PATH', BASE_PATH . "lib/"); 
+4
source share
3 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 reorder the definition of constants to use them directly. Not sure if this helps to read.

+8
source

Firstly:

 realpath(__FILE__) 

just useless

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

 dirname(dirname(__FILE__)) 

.. is the way the file system (its not invented by php;)) defines the parent directory as well . defines the current directory.

+4
source

it should not be in index.php .. it should be in the config / folder, and PUBLIC_PATH is the same as BASE_PATH ... And I don't like to use the dirname and realpath functions, I just write the correct path manually (but it's just me)

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

Source: https://habr.com/ru/post/1347114/


All Articles