views:

46

answers:

1

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 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!

A: 

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');
Cags
Yes it's the simplest, but I can't count on $_SERVER['DOCUMENT_ROOT'] on some client environments.
AlexV
That's somewhat irrelevant, I simply put that for ease of typing, just put your root path in there. The point I was making was, why mess about striping things out etc, when you can simply define a document_root and root_url as independent variables.
Cags
Yeah I know, but with my way, it will work anywhere in any dir in any config. With your way, you have to change the const when you change host or move the files :)
AlexV
I ended up using my define with some functions that strip off the document root (when detected correctly) but you solution is still good (but less "portable").
AlexV