PHP include absolute path

后端 未结 3 2009
遇见更好的自我
遇见更好的自我 2020-12-01 14:11

I have a variable on my site called $basePath which is set as:

$basePath = \'/Systems/dgw/\';

I am using it on all my css, js and images ta

相关标签:
3条回答
  • 2020-12-01 14:49

    You can add an include_path = ".:/home/myuser/mysite.com/" to your php.ini or you can add something like this into your script before the include or require:

    set_include_path(get_include_path() . ":/home/myuser/mysite.com/");
    

    The first one will work for all the scripts running in your website.

    The second option will only work for the script which has the setincludepath on the code, for the rest of the application it will not work unless you have an object you call in every script that add the setincludepath.

    0 讨论(0)
  • 2020-12-01 15:09

    You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :

    <?php 
       $path = $_SERVER['DOCUMENT_ROOT'];
       $path .= "/yourpath/yourfile.php";
       include_once($path);
    ?>
    
    0 讨论(0)
  • 2020-12-01 15:10

    If your server doesn't populate the "document_root", you may need this



        require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");
    

    I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.
    For example, let's say i have this file tree:
    domain.com/aaa/index.php
    domain.com/bbb/ccc/ffffd/index.php
    domain.com/_resources/functions.php

    I can include the functions.php file from wherever i am, just by copy pasting

    require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");
    



    If you need to use this code many times, you may create a function that returns the "str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))" part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named "path_back"):

    require(path_back()."/_resources/another_php_file.php");
    
    0 讨论(0)
提交回复
热议问题