简体   繁体   English

PHP:从绝对 URL 获取绝对路径

[英]PHP: Get absolute path from absolute URL

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

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:文档:

parse_url解析网址

DOCUMENT_ROOT DOCUMENT_ROOT

dirname目录名

You can use the parse_url function to 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).它还取决于没有什么可以阻止 URL 不直接映射到文件系统(例如 mod_rewrite、mod_alias、通过 MVC 框架路由的 URI 等)。 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.psgi and /home/user/recall/root/blog/day.tt but the DocumentRoot would be /home/user/recall/htdocs/ )例如,对于我目前正在使用的系统,如果您要点击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/

Try $_SERVER['DOCUMENT_ROOT'] .试试$_SERVER['DOCUMENT_ROOT'] Assuming a URL like假设一个 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']

try尝试

$filepath = $_SERVER['DOCUMENT_ROOT'].'/rootfolder/filename.php'

this may help you.这可能对你有帮助。

I've found this to work reliably:我发现这可以可靠地工作:

function get_file_path_from_url( $file_url ){
   return realpath($_SERVER['DOCUMENT_ROOT'] . parse_url( $file_url, PHP_URL_PATH ));
}

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

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