How do you know the correct path to use in a PHP require_once() statement

后端 未结 9 2122
别跟我提以往
别跟我提以往 2021-01-31 22:02

As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:

require_on         


        
相关标签:
9条回答
  • 2021-01-31 23:02

    If you have sufficient access rights, try to modify PHP's include_path setting for the whole site. If you cannot do that, you'll either have to route every request through the same PHP script (eg. using Apache mod_rewrite) or you'll have to use an "initialization" script that sets up the include_path:

    $includeDir = realpath(dirname(__FILE__) . '/include'); 
    ini_set('include_path', $includeDir . PATH_SEPARATOR . ini_get('include_path'));
    

    After that file is included, use paths relative to the include directory:

    require_once '../init.php'; // The init-script
    require_once 'MyFile.php'; // Includes /include/MyFile.php
    
    0 讨论(0)
  • 2021-01-31 23:08

    I like to do this:

    require_once(dirname(__FILE__)."/../_include/header.inc");
    

    That way your paths can always be relative to the current file location.

    0 讨论(0)
  • 2021-01-31 23:09

    The path of the PHP file requested in the original GET or POST is essentially the 'working directory' of that script. Any "included" or "required" scripts will inherit that as their working directory as well.

    I will either use absolute paths in require statements or modify PHP's include_path to include any path in my app I may want to use to save me the extra typing. You'll find that in php.ini.

    include_path = ".:/list/of/paths/:/another/path/:/and/another/one"

    I don't know if it'll help you out in this particular instance but the magical constants like FILE and DIR can come in handy if you ever need to know the path a particular file is running in.

    http://us2.php.net/manual/en/language.constants.predefined.php

    0 讨论(0)
提交回复
热议问题