How can I find an application's base url?

后端 未结 11 1390
南方客
南方客 2020-12-16 01:35

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

相关标签:
11条回答
  • 2020-12-16 01:49

    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" />
    
    0 讨论(0)
  • 2020-12-16 01:52

    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.

    0 讨论(0)
  • 2020-12-16 01:56

    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
    
    0 讨论(0)
  • 2020-12-16 01:58

    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?

    0 讨论(0)
  • 2020-12-16 01:59

    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();
    ?>
    
    0 讨论(0)
  • 2020-12-16 02:00

    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.
    0 讨论(0)
提交回复
热议问题