Base URL in PHP

前端 未结 3 1672
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 23:34

I\'ve got a bit of a dilemma, and it\'s been bothering me for quite some time. I have a local testing server that\'s set up like so: 127.0.0.1/

My website i

3条回答
  •  清酒与你
    2021-01-28 00:18

    I’ve tinkered around with most of the $_SERVER[] tags and attributes, as well as parse_url().

    Don’t tinker with them. There’s no clean/automated way to do what you are doing. Just set a base path manually in a config file & don’t worry about it—relative paths—ever again. And if you need to set a base URL, the process is similar.

    So as far as a file base path goes, you should explicitly set a $BASE_PATH like this:

    $BASE_PATH = '/full/path/to/your/codebase/here/';
    

    If you don’t know what your file system base path is, just place this line of code in your PHP code; like index.php:

    echo "Your path is: " . realpath(dirname(__FILE__)) . "
    ";

    Then load that page. Somewhere near the top will be this text:

    Your path is: /full/path/to/your/codebase/here/

    Then with that set you can change your code to be something like this:

    And then set your include_once like this:

    include_once $BASE_PATH  . 'includes/myfile.php';
    

    Some might say you should use $_SERVER['DOCUMENT_ROOT'] or even dirname(__FILE__) directly with the implication being that you can simplify code portability that way. But the way file paths are set for installs can vary so it just never works well & the chances of you getting snagged on an odd server quirk is high.

    It’s always best to just to manually set a $BASE_PATH in a config file when you move code than deal with the headaches caused by PHP constants like $_SERVER not being consistent between installs, setups & configurations.

    And as far as a base URL goes, just follow the same thinking with this being on your local development setup:

    $BASE_URL = '/websitename/';
    

    And this being on your production server:

    $BASE_URL = '/';
    

    So with that $BASE_URL set then you can just do this:

    I’ve got the base script for almost all of the links, except for the including header and footer files.

    Now just prepend any path you might need requested via a URL with $BASE_URL & you should be good to go.

提交回复
热议问题