PHP:从绝对 URL 获取绝对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12242767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Get absolute path from absolute URL
提问by Tariq Aziz
I have an absolute path of a file, Is there a way to get the file absolute path
我有一个文件的绝对路径,有没有办法获取文件的绝对路径
http://domainname/rootfolder/filename.php
and I wanna get something like
我想得到类似的东西
/home/domainname/public_html/foldername/filename.php
/home/domainname/public_html/foldername/filename.php
回答by carlosveucv
This is the easiest way:
这是最简单的方法:
$path = parse_url('http://domainname/rootfolder/filename.php', PHP_URL_PATH);
//To get the dir, use: dirname($path)
echo $_SERVER['DOCUMENT_ROOT'] . $path;
That'll print you the full path.
那会打印出完整的路径。
Documentation:
文档:
回答by Quentin
You can use the parse_urlfunctionto get the local part of the URL.
您可以使用该parse_url函数来获取 URL 的本地部分。
Converting that into a file path then requires that you know where the document root of the webserver is. If it is the same server as the one the page is running on, then you can usually get that from $_SERVER['DOCUMENT_ROOT'].
然后将其转换为文件路径需要您知道网络服务器的文档根目录在哪里。如果它与运行页面的服务器在同一台服务器上,那么您通常可以从$_SERVER['DOCUMENT_ROOT'].
It also depends on there being nothing preventing the URL from not being a direct mapping onto a file system (such as mod_rewrite, mod_alias, URIs being routed through an MVC framework, etc). For example, for a system I'm working on at the moment, if you were to hit http://example.com/blog/2012/01/01/then the files involved would be /home/user/recall/script/recall.psgiand /home/user/recall/root/blog/day.ttbut the DocumentRoot would be /home/user/recall/htdocs/)
它还取决于没有什么可以阻止 URL 不直接映射到文件系统(例如 mod_rewrite、mod_alias、通过 MVC 框架路由的 URI 等)。例如,对于我目前正在使用的系统,如果您要点击http://example.com/blog/2012/01/01/那么所涉及的文件将是/home/user/recall/script /recall.psgi和/home/user/recall/root/blog/day.tt但 DocumentRoot 将是/home/user/recall/htdocs/)
回答by Marc B
Try $_SERVER['DOCUMENT_ROOT']. Assuming a URL like
试试$_SERVER['DOCUMENT_ROOT']。假设一个 URL 像
http://example.com/subfolder/somefile.html
and the file's actual location on the server being
并且文件在服务器上的实际位置是
/home/sites/example.com/html/subfolder/somefile.html
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- $_SERVER['DOCUMENT_ROOT']
回答by user3415227
try
尝试
$filepath = $_SERVER['DOCUMENT_ROOT'].'/rootfolder/filename.php'
this may help you.
这可能对你有帮助。

