[英]Get root url of the site in PHP
Consider my project directory structure as follows, 考虑我的项目目录结构,如下所示:
-public_html
-projects
-folder1
index.php \\code is written here
+folder2
+downloads
I am trying to get the root directory through $_SERVER['DOCUMENT_ROOT']
, but it seems the returned string is not in the form I expect. 我正在尝试通过
$_SERVER['DOCUMENT_ROOT']
获取根目录,但似乎返回的字符串不是我期望的形式。
My directory inside my website is (basically in) public_html/projects/folder1
. 我在网站内的目录(基本上在
public_html/projects/folder1
。 Using document root, the returned string is as follows when implemented on a website, /home/site_name/public_html
which is not going to work if the link is to be shared, cause I am using it to store the file in a directory. 使用文档根目录,在网站
/home/site_name/public_html
上实现时,返回的字符串如下所示,如果要共享链接,该字符串将不起作用,因为我使用它来将文件存储在目录中。 So, I want something like it should return, www.site_name.com/downloads
所以,我希望类似的东西可以返回,
www.site_name.com/downloads
The __DIR__
is giving the whole document path from where it is called( folder1/index.php
), but I want to get into the main folder ( public_html/downloads
), not in the same folder as the index file is. __DIR__
给出了整个文档的路径,从那里被称为( folder1/index.php
),但是我想进入主文件夹( public_html/downloads
),而不是与索引文件位于同一文件夹中。
Are there any other php functions that can help to reach the downloads folder in public_html and which can be accessed like, www.sitename.com/downloads/... 是否有任何其他php函数可以帮助访问public_html中的downloads文件夹 ,并且可以像www.sitename.com/downloads/那样进行访问。
To return the folder of current php file, use this script. 要返回当前php文件的文件夹,请使用此脚本。
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;
You want to use $_SERVER['SERVER_NAME']
to get the root URL of the site. 您想使用
$_SERVER['SERVER_NAME']
获取网站的根URL。 You can use this to get a URL to your downloads folder. 您可以使用它来获取下载文件夹的URL。
$downloads_url = $_SERVER['SERVER_NAME'] . '/downloads/';
constants.php: constants.php:
define('PROTOCOL',(!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://',true);
define('DOMAIN',$_SERVER['HTTP_HOST']);
define('ROOT_URL', preg_replace("/\/$/",'',PROTOCOL.DOMAIN.str_replace(array('\\',"index.php","index.html"), '', dirname(htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES))),1).'/',true);// Remove backslashes for Windows compatibility
Then, in the the index of the project use
it 然后,在项目的索引中
use
它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.