Making php includes work in a sub-directory

后端 未结 4 1530
北海茫月
北海茫月 2020-12-29 12:57

Ok, I am creating an admin interface for my custom blog at the url /admin.

Is it possible for me to be able to use the same includes (including autoload), as the roo

相关标签:
4条回答
  • 2020-12-29 13:22

    Another option that I've used for functions.php in the past is a class autoloader.

    //Class Autoloader
    spl_autoload_register(function ($className) {
    
        $className = strtolower($className);
        $path = "includes/{$className}.php";
    
        if (file_exists($path)) {
    
            require_once($path);
    
        } else {
    
            die("The file {$className}.php could not be found.");
    
        }
    });
    

    This works under certain circumstances and has been helpful to me in the past when I don't want to define an absolute $root url.

    0 讨论(0)
  • 2020-12-29 13:27

    Easiest way would be to use absolute pathes / URLs.

    For the URLs, define a constant/variable somewhere, that points to the root of your application, like :

    define('ROOT_URL', 'http://www.example.com');
    

    or

    $root_url = 'http://www.example.com';
    

    And use it in every link, like :

    <a href="{$root_url}/my-page.php">blah</a>
    

    This way, always OK (and the day you install your project on another server, or in a subdirectory, you only have one constant/variable to modify, and everything still works)

    For includes / requires, always use absolute pathes too ; one solution is to use dirname, like this :

    include dirname(__FILE__) . '/my_file.php';
    include dirname(__FILE__) . '/../my-other-file.php';
    

    __FILE__ is the current file, where you are writing this line ; dirname gets the path (the full path) to the directory containing that file.

    With that, you never have to worry about the relative paths of your files.

    0 讨论(0)
  • 2020-12-29 13:30

    Yet another answer would be similar to combining the first two suggestions. You could define the constant:

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

    Then, assuming that config.php needs to be included in many files of the site then you can use the following statement to accomplish this:

    include(ABSPATH.'config.php');
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-29 13:42

    The best practice for this is to define a 'ABSOLUTE_PATH' constant that contains the directory that everything is located under. After that, you can simply copy and paste everything, because it is defining the 'full' path, which doesn't change from directory to directory.

    Example

    define("ABS_PATH", $_SERVER['DOCUMENT_ROOT']);
    
    or
    
    define("ABS_PATH", dirname(__FILE__));
    // This defines the path as the directory the file is in.
    

    Then at any point you can simply do this to include a file

    include(ABS_PATH . "/path/to/file");
    
    0 讨论(0)
提交回复
热议问题