我在php中的相对路径上遇到了一些问题。 在我的一个类中,我有以下代码:
$iniPath = $_SERVER['DOCUMENT_ROOT'] . "/movies/config.ini";
$ini_array = parse_ini_file($iniPath, true);
这段代码运行良好,因为它返回"/var/www/movies/config.ini"。
但问题是代码不可传输。 如果它安装在另一台服务器上,他们可能不会将其安装在/movies/中。
如何在 php 中将应用程序目录指定为根目录?
您可以使用
__DIR__
或dirname(__FILE__)
来确定相对于应用程序的当前路径。
您可以在第一个文件中定义一个常量,称为(或在配置或引导程序中):
<?php
define('ROOT_DIR', __DIR__.'/');
// and define some other base path
// you can also define everything in a separate file
define('MOVIE_DIR', ROOT_DIR.'movies/');
// and define absolute path
define('CLASS_DIR', '/usr/local/share/something/that/will/never/change/');
// then your code will looks like
$iniPath = MOVIE_DIR . '/config.ini';
$ini_array = parse_ini_file($iniPath, true);
编辑:另一种选择(在阅读您在问题中的评论后)是使用set_include_path但并不经常使用。
尝试查看 PHP 魔术常量
__DIR__
http://php.net/manual/en/language.constants.predefined.php