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

后端 未结 9 2126
别跟我提以往
别跟我提以往 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 22:44

    I use the dirname(__FILE__) thing like bobwienholt most the time, but what it could pay to do is have a base entry point that loads all your other code that defines a constant refereing to the root of the project, ie

    define("ROOT",dirname(__FILE__).'/' ); 
    

    and then later all you need to know is where the path is relative to root, ie:

    require(ROOT . "/lib/tool/error.php"); 
    

    note,

    you should REALLY avoid paths with "../" at the start of them, they are not relative to the file, but relative to where you ARE and this creates broken-ass code.

     cd foo
     php bar/baz.php 
     -> some error saying it cant find the file
     cd bar 
     php baz.php 
     -> suddenly working.
    

    Important

    If you use "../" notation, it takes complete ignorance of the PHP Include Path, And ONLY considers where the person whom is running it is.

提交回复
热议问题