PHP Dynamically get complete Absolute URL Path for specific file that will be included in other files

你离开我真会死。 提交于 2019-12-05 17:02:56

If you can rely on the value of $_SERVER[ 'DOCUMENT_ROOT' ], then inside configuration.php:

$path = substr( __FILE__, strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) );

$url = "www.mydomain.com{$path}";

If it fits your use case, you can make it more dynamic using $_SERVER[ 'HTTP_HOST' ];

DOCUMENT_ROOT

I've used DOCUMENT_ROOT liberally in my development, as it's often the only dynamic variable available for constructing certain self-referential paths. There's a looong running Apache bug ticket (#26052) about how DOCUMENT_ROOT is poorly handled, particularly that Apache wouldn't allow you to set the value with RewriteRule and didn't set it to a sensible value when using mod_vhost_alias. The discussion goes on over a period of 7-8 years as people presumably from the Apache project resist changing the behavior, until they finally came around and made a change this year in 2.4.1. (I looked into this previously, but I forget now what the exact changes were, and how satisfying they are.)

If you look at the comments on the ticket you'll see people resisting changes to the behavior with comments like:

Don't trust the DOCUMENT_ROOT variable.

DOCUMENT_ROOT is not, never was, and never will be a reliable way of finding the filesystem path to web content.

So I suggest reading the comments on that ticket to see what people are saying the caveats of using it are. I've used it with a lot of success and don't know of a better way to achieve the same things in the same situations that DOCUMENT_ROOT is available and provides the necessary data.

laromicas

What I used, which worked perfectly for what I wanted, was this:

define('URL', dirname(substr($_SERVER['SCRIPT_FILENAME'], strlen( $_SERVER[ 'DOCUMENT_ROOT' ] ) )).'/');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!