Including files using relative paths with PHP?

后端 未结 4 659
暖寄归人
暖寄归人 2020-12-12 06:50

When developing my website I called all the includes in my php files by calling one single file called includes.

The code of this file looked somethig like this: (I

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 07:43

    First off, don't abuse ternary syntax like that. Instead of defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);, you can use the OR operator (which will short-circuit on a boolean true result):

    defined('DS') OR define('DS', DIRECTORY_SEPARATOR);
    

    Secondly, if this is inside of a bootstrap file that you know the position of, simply use dirname(__FILE__):

    defined('SITE_ROOT') OR define('SITE_ROOT', dirname(__FILE__));
    

    Otherwise, if you know the relative position of the root, you can use multiple dirname calls. So if it's the parent directory of the present one:

    defined('SITE_ROOT') OR define('SITE_ROOT', dirname(dirname(__FILE__)));
    

    Don't use $_SERVER['DOCUMENT_ROOT'] or cwd() or hardcode your path. Always use dirname(__FILE__) to determine the absolute path. For more info on why, see This Answer

提交回复
热议问题