Site-root relative path doesn't work

后端 未结 5 771
死守一世寂寞
死守一世寂寞 2021-01-27 21:37

I\'m not understanding this. It\'s screwing up whole site because I\'m using a php template.

Supposedly beginning a link with \'/\' starts me at the root according to ev

5条回答
  •  爱一瞬间的悲伤
    2021-01-27 22:16

    Stop worrying about relative path by just using a base path set as a configuration so you are not constantly juggling relative locations. For example, in your main config file, you can define a base path like this:

    $BASE_PATH = '/the/path/to/the/codebase/';
    

    If you don’t know the base path to your files, then place this line at the top of your PHP code:

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

    And load that page. Somewhere near the top should be a line that reads:

    Your path is: /the/path/to/the/codebase/

    Of course /the/path/to/the/codebase/ will be your actual file path, but that will be your base path. Then just set $BASE_PATH to that value.

    Then when you do an require, the syntax would be:

    require($BASE_PATH . '/cis130/textfiles/php/variables.php');
    

    The benefit of this is no matter how deeply nested your codebase becomes, you will always be anchored to the value of $BASE_PATH. And your life will be made tons easier thanks to not having to worry about relative path issues.

    I would also recommend using require_once instead of require to avoid scenarios where your script might inadvertently attempt to load the same file more than once.

    require_once($BASE_PATH . '/cis130/textfiles/php/variables.php');
    

提交回复
热议问题