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

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

    The current working directory for PHP is the directory in which the called script file is located. If your files looked like this:

    /A
       foo.php
       tar.php
       B/
           bar.php
    

    If you call foo.php (ex: http://example.com/foo.php), the working directory will be /A/. If you call bar.php (ex: http://example.com/B/bar.php), the working directory will be /A/B/.

    There is where it gets tricky. Let us say that foo.php is such:

    
    

    And bar.php is:

    
    

    If we call foo.php, then bar.php will successfully call tar.php because tar.php and foo.php are in the same directory which happens to be the working directory. If you instead call bar.php, it will fail.

    Generally you will see either in all files:

    require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' );
    

    or with the config file:

    // config file
    define( "APP_ROOT", realpath( dirname( __FILE__ ) ).'/' );
    

    with the rest of the files using:

    require_once( APP_ROOT.'../../path/to/file.php' );
    

提交回复
热议问题