10

I'd like to find the base url of my application, so I can automatically reference other files in my application tree...

So given a file config.php in the base of my application, if a file in a subdirectory includes it, knows what to prefix a url with.

application/config.php
application/admin/something.php
application/css/style.css

So given that http://www.example.com/application/admin/something.php is accessed, I want it to be able to know that the css file is in $approot/css/style.css. In this case, $approot is "/application" but I'd like it to know if the application is installed elsewhere.

I'm not sure if it's possible, many applications (phpMyAdmin, Squirrelmail I think) have to set a config variable to begin with. It would be more user friendly if it just knew.

DGM
  • 26,629
  • 7
  • 58
  • 79

11 Answers11

16

I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it.

define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');

$tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));
$tempPath2 = explode('/', substr(ABSPATH, 0, -1));
$tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));

for ($i = count($tempPath2); $i < count($tempPath1); $i++)
    array_pop ($tempPath3);

$urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);

if ($urladdr{strlen($urladdr) - 1}== '/')
    define('URLADDR', 'http://' . $urladdr);
else
    define('URLADDR', 'http://' . $urladdr . '/');

unset($tempPath1, $tempPath2, $tempPath3, $urladdr);

The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations.

Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • No it doesn’t. It returns the physical filesystem path and not the URL path. – Gumbo Mar 19 '09 at 22:23
  • ABSPATH returns the physical filesystem path, URLADDR returns the fully qualified URL of the application. – Andrew Moore Mar 20 '09 at 00:09
  • whoops, no, there's still something missing. I got ABSPATH=/path/to/real/application and URLADDR=http://hostname/ I guess I wanted URLADDR to be http://hostname/application/ – DGM Mar 20 '09 at 16:07
  • Andrew, this was right, if I just remove one of the dirname() calls in the first line - the ABSPATH removed one too many directories. If you can edit the post to have only one dirname, I'll re-mark it as correct. – DGM Mar 20 '09 at 16:43
  • You are right, sorry. I have this code running in an includes/ folder up of my root application directory, hence the extra dirname(). Changed! – Andrew Moore Mar 20 '09 at 17:35
5

You can find the base url with the folowing code:

define('SITE_BASE_PATH','http://'.preg_replace('/[^a-zA-Z0-9]/i','',$_SERVER['HTTP_HOST']).'/'.str_replace('\\','/',substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']))).'/');

Short and best.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Murtaza Baig
  • 211
  • 4
  • 3
  • I would suggest to include a little "." after that "....0-9" if you want it to work on ip-addresses too. ----> `define('SITE_BASE_PATH','http://'.preg_replace('/[^a-zA-Z0-9.]/i','',$_SERVER['HTTP_HOST']).'/'.str_replace('\\','/',substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']))).'/'); ` – K. Kilian Lindberg Dec 11 '13 at 14:20
  • Why `str_replace("\\"` ?? – TCB13 Mar 09 '15 at 23:56
2

The REQUEST_URI combined with dirname() can tell you your current directory, relevant to the URL path:

<?php
  echo  dirname($_SERVER["REQUEST_URI"]);
?>

So http://example.com/test/test.php prints "/test" or http://example.com/ prints "/" which you can use for generating links to refer to other pages relative to the current path.

EDIT: just realized on re-reading that you might be asking about the on-disk path as opposed to the URL path. In that case, you want PHP's getcwd() function instead:

<?php
  echo  getcwd();
?>
Jay
  • 41,768
  • 14
  • 66
  • 83
1

Unless you track this yourself, I don't believe this would have a definition. Or rather, you're asking PHP to track something that you're somewhat arbitrarily defining.

The long and short of it is, if I'm understanding your question correctly, I don't believe what you're asking for exists, at least not as "core" PHP; a given framework may provide a "root" URL relative to a directory structure that it understands.

Does that make sense?

theraccoonbear
  • 4,283
  • 3
  • 33
  • 41
1

Put this in your config.php (which is in your app's root dir):

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

I think that'll do it.

Lucas Oman
  • 15,597
  • 2
  • 44
  • 45
1

url root of the application can be found by

$protocol = (strstr('https',$_SERVER['SERVER_PROTOCOL']) === false)?'http':'https';
$url = $protocol.'://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI']);

this code will return url path of any application whether be online or on offline server.

I've not made proper check for proper '/'. Please modify it for slashes.

this file should be placed in root.

example : if application url :

http://localhost/test/test/test.php

then this code will return

http://localhost/test/test

Thanks

Leo
  • 37,640
  • 8
  • 75
  • 100
0

One solution would be to use relative paths for everything, that way it does not matter where the app is installed. For example, to get to your style sheet, use this:

../css/style.css
Adam Pierce
  • 33,531
  • 22
  • 69
  • 89
  • 2
    The problem is that this is in a template, but potentially called from different levels, so I need to know what level to call based on the script, or else I need the full url – DGM Oct 07 '08 at 00:36
0

If you want the path on the filesystem you can use $_SERVER['DOCUMENT_ROOT']
If you just want the path of the file that appears in the URL after the domain use $_SERVER['REQUEST_URI']

UnkwnTech
  • 88,102
  • 65
  • 184
  • 229
0

I've never found a way to make it so.

I always end up setting a config variable with the server path to one level above web root. Then it's:

  • $configVar . 'public/whatever/' for stuff inside root,
  • but you can also include from outside with $configVar . 'phpInc/db.inc.php/' etc.
da5id
  • 9,100
  • 9
  • 39
  • 53
0

This works like a charm for me, anywhere I deploy, with or without rewrite rules:

$baseDir = 'http://'.$_SERVER['HTTP_HOST'].(dirname($_SERVER['SCRIPT_NAME']) != '/' ? dirname($_SERVER["SCRIPT_NAME"]).'/' : '/');

SchizoDuckie
  • 9,353
  • 6
  • 33
  • 40
  • 1
    This comes close, but it doesn't shave off subdirectories of the application from the url. So if I'm in http://hostname/application/subfolder/test.php and including a file in /application that defines this variable, it still has subfolder in the url. I want only /application – DGM Mar 20 '09 at 16:24
  • Try URL rewriting. Just rewrite everything to an index.php in /application/ (except some http resources ofcourse) Make that index.php forward it to the correct subfolder. – SchizoDuckie Mar 20 '09 at 17:59
  • Enable mod_rewrite in apache .htaccess in /application/ RewriteEngine On RewriteRule ^includes/ - [L] [OR] #do not apply to /includes OR RewriteRule ^images/ - [L] #do not apply to /images RewriteRule ^.* index.php #rewrite everything to index.php Parse $_SERVER['REQUEST_URI'] for your path! – SchizoDuckie Mar 20 '09 at 18:01
0

This is what I have used in my app which works fine, I also use a custom port so I had to allow for this also.

define('DOC_URL', ($_SERVER['HTTPS']=='on'?'https':'http').'://'.$_SERVER['SERVER_NAME'].(!in_array($_SERVER['SERVER_PORT'], array(80,443))?':'.$_SERVER['SERVER_PORT']:'')).dirname($_SERVER['REQUEST_URI']);

Then I use it by typing the following...

<img src="<?php echo DOC_URL; ?>/_img/logo.png" />