简体   繁体   English

PHP绝对根路径和根URL

[英]PHP absolute root path and root url

Im trying to define the absolute root path and the root url of my app. 我试图定义我的应用程序的绝对根路径和根URL。 I tried this , however I can't understand something yet. 我尝试了这个 ,但是我还不明白。

I have created config.inc.php in the root folder with the code in the answer. 我已经在root文件夹中使用答案中的代码创建了config.inc.php Also I have the file index.php in the root in which I include config.inc.php and the constanst are fine. 另外我在root中有index.php文件,其中包含config.inc.php和constanst都很好。 But I have another file in ${ROOT}/example/file.php where I also include config.inc.php but the root url contains the example folder in the end. 但我在${ROOT}/example/file.php中有另一个文件,其中我还包括config.inc.php但根URL包含最后的示例文件夹。

The app structure is: 应用程序结构是:

config.inc.php
index.php
example/file.php

How can I always have the absolute root path and the root url of my app? 我怎么能始终拥有我的应用程序的绝对根路径和根URL?

Thanks! 谢谢!

Absolute root path: 绝对根路径:

$_SERVER['DOCUMENT_ROOT']

Path from the root folder: 根文件夹中的路径:

dirname($_SERVER['PHP_SELF'])

You can manually type an absolute and root url in config file and when include it he give you an variable with absolute and root url. 您可以在配置文件中手动键入绝对和根URL,并且在包含它时,他会为您提供具有绝对和根URL的变量。 For root directory you can use an $_SERVER['DOCUMENT_ROOT'] . 对于根目录,您可以使用$_SERVER['DOCUMENT_ROOT']

I've always used the following code in my php apps: 我总是在我的php应用程序中使用以下代码:

** config.php ** ** config.php **

$base = str_replace(
    $_SERVER['DOCUMENT_ROOT'],
    '',
    realpath(dirname(__FILE__)));

$base = ($base == '') ? '/' : '';

You can include this file from anywhere and it will give the base uri of the folder config.php is in. 您可以从任何地方包含此文件,它将提供config.php所在文件夹的基本uri。

如果您正在使用Windows上的文件,那么您可能需要使用两者

$full_path = $_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM