views:

18

answers:

1

I'm having some issues with defined absolute paths in PHP. I define the SITE_ROOT and APP_PATH like so:

defined('SITE_ROOT') ? null : 
define('SITE_ROOT', str_replace('//','/',dirname(__FILE__)) );

defined('APP_PATH') ? null : define('APP_PATH', SITE_ROOT.DS.'application');

When using the APP_PATH in an application like so:

echo APP_PATH;

...this is what I get:

/Users/user/Sites/MyWebsite/application

What I want is for the output to be:

localhost/application

Is there any non-kludgy way of doing this?

My use case is to use the APP_PATH (already in use for doing all my require()'s) echoed out with HTML to avoid relative pathing problems within URLs for href's.

+1  A: 

The __FILE__ constant contains the file path, nothing else. Look at $_SERVER['REQUEST_URI'] and $_SERVER['HTTP_HOST'] to find out what URL was used to invoke the script. This is environment information that must be supplied by the web server that initiated the PHP script (e.g. Apache), it's not something PHP inherently knows.

deceze
Great, thanks! Since my plan is to have this code easily portable from my local dev env to my prod env, would you recommend establishing two separate paths? One would use `$_SERVER['HTTP_HOST']` and the other mentioned above. Or are there any problems with this approach? And are there any potential gotchas if you're deployed across multiple servers?
Josh Smith
@Josh First of all, you shouldn't include the host in your links, but use absolute paths without host (i.e. `/application/page/foo`). This solves relative URL problems without overcomplicating things. Secondly, it really depends on your app how to do this elegantly. If you're using a Dispatcher model (one specific .php file is always invoked, which dispatches the request to other files) it's relatively simple to figure out "where you are", so you don't have to do any system specific configuration. Have a look at any of the popular PHP frameworks for examples.
deceze
I have an initialize.php file that does what I think you're saying. I'm pretty sure the `$_SERVER['HTTP_HOST']` is simply doing what I should be typing manually in the initializer file. Then I can use, say, a `VIEW_URL` path to access the views. Trying it out now to see.
Josh Smith
Yeah, essentially all I really need is this: `defined('VIEW_URL') ? null : define('VIEW_URL', '/application/views');` That allows me to call `VIEW_URL` anywhere in the app without having to constantly figure out the absolute URL.
Josh Smith