How to programmatically determine the document root in PHP?

后端 未结 6 1820
猫巷女王i
猫巷女王i 2020-12-15 13:28

Here\'s a problem that I\'ve been running into lately - a misconfigured apache on a webhost. This means that all scripts that rely on $_SERVER[\'DOCUMENT_ROOT\']

6条回答
  •  再見小時候
    2020-12-15 14:07

    This is one reason why people siphon everything through a bootstrap /index.php using htaccess and/or query strings. You can use the dirname( __FILE__ ) trick noted above and get the public base of your app that way.

    If you're too far into it to switch to a single entry point, one thing I've seen people do is have a common header to their script which walks up the directory tree to find a file which is unique to the base dir:

    function findAppBase( $dir ) {
        if( file_exists( "$dir/unique_file.txt" ) ) {
            return $dir;
    
        return findAppBase( dirname( $dir ) );
    }
    
    $base = findAppBase( dirname( __FILE__ ) );
    

    That code hasn't been tested, and there might be a slicker way using the vars in $_ENV or $_SERVER that will do what you want...

提交回复
热议问题