PHP: Get absolute path from absolute URL

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 06:12:39

问题


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


回答1:


You can use the parse_url function to get the local part of the 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'].

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.psgi and /home/user/recall/root/blog/day.tt but the DocumentRoot would be /home/user/recall/htdocs/)




回答2:


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

dirname




回答3:


Try $_SERVER['DOCUMENT_ROOT']. Assuming a URL like

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']



回答4:


try

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

this may help you.



来源:https://stackoverflow.com/questions/12242767/php-get-absolute-path-from-absolute-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!