开发者

Strip document root from full server path in PHP

OK, I have defined a PHP constant that points to a file on the server like this:

define('SOME_FILE', str_replace('//', '/', str_replace('\\', '/', dirname(__FILE__) . '/foo-bar.txt')));

SOME_FILE will contain a full path + filename which is useble in PHP functions like include, fopen, etc. Now if I want to use this path as an URL in my (X)HTML output, I'm screwed. To do so, I need to strip off开发者_Python百科 the document root.

Usually, $_SERVER['DOCUMENT_ROOT'] is set in 99% of PHP environments, but it can happen where it's poorly configured, overwritten by the user or even missing.

Now what I want to do is to define() another PHP constant based on SOME_FILE that will point to the actual URL of the file (the document root path is stripped off).

I know I can do this in 3-4 lines of code with __FILE__, $_SERVER['SCRIPT_NAME'] (SCRIPT_NAME is required as per CGI 1.1 specification but not DOCUMENT_ROOT), strrpos, and substr, but I'm looking for a "one line" solution to use in a define statement...

I use PHP 5.1.0+. Amy suggestions welcome!


Simplest solution is probably to have a second set of Consts for remote URLs.

define('ROOT_PATH', $_SERVER['DOCUMENT_ROOT']);
define('ROOT_URL', 'http://domain.com');
define('BLAH_PATH', ROOT_PATH . PATH_SEPARATOR . 'blah.php');
define('BLAH_URL', ROOT_URL . PATH_SEPERATOR . 'blah.php');


    $docRoot = str_ireplace('/', '\\', $_SERVER['DOCUMENT_ROOT']); $f = str_ireplace($docRoot, '', $f);

OK. So I cheated a bit. It IS one line but two statements. I could make it one statement but it'd be harder to understand. Just substitute the first str_ireplace for $docRoot in the second statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜